Articles in this section
Category / Section

How to conditionally handle the swiping using MVVM in Xamarin.Forms ListView (SfListView)

1 min read

You can conditionally swipe the ListViewItem from ViewModel by using EventToCommandBehavior in Xamarin.Forms SfListView.

XAML

Define the EventToCommandBehavior for SfListView and bind the ViewModel command for the SwipeStarted event.

<syncfusion:SfListView x:Name="listView" ItemSpacing="1" AllowSwiping="True" AutoFitMode="Height" SelectionMode="None" ItemsSource="{Binding ContactsInfo}">
    <syncfusion:SfListView.Behaviors>
        <local:EventToCommandBehavior EventName="SwipeStarted" Command="{Binding SwipeStartedCommand}"/>
    </syncfusion:SfListView.Behaviors>
    <syncfusion:SfListView.ItemTemplate >
        <DataTemplate>
            <Grid x:Name="grid" BackgroundColor="{Binding BackgroundColor}">
                ...
            </Grid>
        </DataTemplate>
    </syncfusion:SfListView.ItemTemplate>
    <syncfusion:SfListView.LeftSwipeTemplate>
        <DataTemplate>
            <Grid BackgroundColor="Black">
                <Label Text="Left Swipe" TextColor="White" FontAttributes="Bold" VerticalTextAlignment="Center" HorizontalTextAlignment="Center"/>
            </Grid>
        </DataTemplate>
    </syncfusion:SfListView.LeftSwipeTemplate>
</syncfusion:SfListView>

C#

The default command parameter of the SwipeStarted event is SwipeStartedEventArgs. And, from the SwipeStartedEventArgs.ItemData property, you can get the swiped item details and conditionally cancel the swipe based on the data.

namespace ListViewXamarin
{
    public class ContactsViewModel : INotifyPropertyChanged
    {
        public Command<object> SwipeStartedCommand { get; set; }
 
        public ContactsViewModel()
        {
            SwipeStartedCommand = new Command<object>(OnSwipeStarted);
        }
 
        private void OnSwipeStarted(object obj)
        {
            var args = obj as Syncfusion.ListView.XForms.SwipeStartedEventArgs;
            if ((args.ItemData as Contacts).BackgroundColor == Color.LightGray)
            {
                args.Cancel = true;
            }
        }
    }
}

View sample in GitHub

demo image to conditionally swipe the ListViewItem in Xamarin.Forms SfListView

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied