How to bind a command in .NET MAUI Accordion (SfAccordion)?
This guide demonstrates how to bind a Command to the content of an AccordionItem in .NET MAUI Accordion.
C#
The ItemInfoRepository
class contains a command that will be bound in the XAML.
public class ItemInfoRepository
{
public Command<object> ShowDetailsCommand { get; set; }
public ItemInfoRepository()
{
ShowDetailsCommand = new Command<object>(OnShowDetailClicked);
}
private void OnShowDetailClicked(object obj)
{
var item = obj as ItemInfo;
App.Current!.MainPage!.DisplayAlert(item!.Name, item.Description, "Ok");
}
}
XAML
Bind the ViewModel Command to the ImageButton that is loaded inside the Content of the AccordionItem.
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:accordion="clr-namespace:Syncfusion.Maui.Accordion;assembly=Syncfusion.Maui.Expander"
xmlns:local="clr-namespace:Accordion"
x:Class="Accordion.MainPage">
<ContentPage.BindingContext>
<local:ItemInfoRepository x:Name="viewModel"/>
</ContentPage.BindingContext>
<accordion:SfAccordion x:Name="accordion" BindableLayout.ItemsSource="{Binding Info}" ExpandMode="SingleOrNone">
<BindableLayout.ItemTemplate>
<DataTemplate>
<accordion:AccordionItem>
<accordion:AccordionItem.Header>
<Grid Padding="5,0,0,0" HeightRequest="50">
<Label Text="{Binding Name}" FontSize="20" />
</Grid>
</accordion:AccordionItem.Header>
<accordion:AccordionItem.Content>
<Grid BackgroundColor="#C0C0C0" Padding="5,0,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="45" />
</Grid.ColumnDefinitions>
<Label Text="{Binding Description}" VerticalOptions="Center"/>
<Grid Grid.Column="1" Padding="10" BackgroundColor="#C0C0C0">
<ImageButton BackgroundColor="{OnPlatform WinUI=#C0C0C0}" HeightRequest="30" WidthRequest="30" Source="Details.png" Command="{Binding Path=BindingContext.ShowDetailsCommand, Source={x:Reference accordion}}" CommandParameter="{Binding .}"/>
</Grid>
</Grid>
</accordion:AccordionItem.Content>
</accordion:AccordionItem>
</DataTemplate>
</BindableLayout.ItemTemplate>
</accordion:SfAccordion>
</ContentPage>
Download the complete sample on GitHub.
Conclusion
I hope you enjoyed learning how to bind the command in .NET MAUI Accordion.
You can refer to our .NET MAUI Accordion feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started with configuration specifications. Explore our .NET MAUI Accordion example to understand how to create and manipulate data.
For current customers, check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.
Please let us know in the comments section if you have any queries or require clarification. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!