Category / Section
How to bind Command to Expander in ItemTemplate of Xamarin.Forms ListView (SfListView)
When the SfExpander is loaded in the ListView.ItemTemplate, the ListView.ItemTapped event is not triggered in Android and iOS. Since, the touch flow was handled using the Tunneling-Bubbling concept in the framework. You can refer to the framework report from here. Also, You can use EventToCommandBehavior to bind the Command for Expand/Collapse events in SfExpander using to handle the tap action in Xamarin.Forms.
XAML
Using EventToCommandBehavior, bind the Command to the Expanding event. Also, bind the ItemData to the CommandParameter.
<sflistview:SfListView x:Name="listView" AutoFitMode="DynamicHeight" ItemsSource="{Binding ContactsInfo}">
<sflistview:SfListView.ItemTemplate>
<DataTemplate>
<Frame x:Name="frame" CornerRadius="2" Padding="{OnPlatform Android=1, iOS=1, UWP=0}" Margin="{OnPlatform Android=1, iOS=1, UWP=0}" OutlineColor="White" HasShadow="{OnPlatform Android=true, iOS=false, UWP=true}">
<Grid Padding="{OnPlatform Android=2, iOS=2, UWP=0}" Margin="{OnPlatform Android=1, iOS=1, UWP=0}" BackgroundColor="White" >
<expander:SfExpander x:Name="expander" HeaderIconPosition="None">
<expander:SfExpander.Behaviors>
<local:EventToCommandBehavior Command="{Binding Path=BindingContext.ExpandingCommand, Source={x:Reference listView}}" EventName="Expanding" CommandParameter="{Binding .}"/>
</expander:SfExpander.Behaviors>
<expander:SfExpander.Header>
...
</expander:SfExpander.Header>
<expander:SfExpander.Content>
...
</expander:SfExpander.Content>
</expander:SfExpander>
</Grid>
</Frame>
</DataTemplate>
</sflistview:SfListView.ItemTemplate>
</sflistview:SfListView>
C#
Define the Command that is bound to the SfExpander.Expanding event.
public class ViewModel : INotifyPropertyChanged
{
private Command<Object> expandingCommand;
public Command<object> ExpandingCommand
{
get { return expandingCommand; }
set { expandingCommand = value; }
}
public ViewModel()
{
ExpandingCommand = new Command<object>(ExpandingCommandMethod);
}
private void ExpandingCommandMethod(object obj)
{
App.Current.MainPage.DisplayAlert("Alert!", "" + (obj as Contact).ContactName + " expanded", "Ok");
}
}
