Category / Section
How to swipe an item programatically in Xamarin.Forms ListView
1 min read
You can swipe an item programmatically by using the SwipeItem method of Xamarin.Forms SfListView.
XAML
<ContentPage.Content> <StackLayout> <Grid HeightRequest="50"> <Button x:Name="RightSwipe" Text="Right Swipe Button" /> <Button x:Name="LeftSwipe" Text="Left Swipe Button" Grid.Column="1"/> </Grid> <listView:SfListView x:Name="listView" ItemSize="70" SelectionMode="Single" AllowSwiping="True" ItemSpacing="0,0,5,0" > <listView:SfListView.LeftSwipeTemplate> <DataTemplate> <ViewCell> <ViewCell.View> <Grid BackgroundColor="SlateBlue" HorizontalOptions="Fill" VerticalOptions="Fill"> <Label Text="Left Swipe Template" TextColor="White" VerticalOptions="Center" HorizontalOptions="Center"/> </Grid> </ViewCell.View> </ViewCell> </DataTemplate> </listView:SfListView.LeftSwipeTemplate> <listView:SfListView.RightSwipeTemplate> <DataTemplate> <ViewCell> <ViewCell.View> <Grid BackgroundColor="SlateBlue" HorizontalOptions="Fill" VerticalOptions="Fill"> <Label Text="Right Swipe Template" TextColor="White" VerticalOptions="Center"/> </Grid> </ViewCell.View> </ViewCell> </DataTemplate> </listView:SfListView.RightSwipeTemplate> </listView:SfListView> </StackLayout> </ContentPage.Content>
C#
You need to pass the item to be swiped and SwipeOffset as parameter in the SwipeItem method. The SwipeOffset value should be positive for LeftSwiping of ListViewItem.
private void LeftSwipeButton_Clicked(object sender, EventArgs e) { ListView.SwipeItem(viewModel.contactsinfo[1], 200); }
The SwipeOffset value should be negative for RightSwiping of ListViewItem.
private void RightSwipeButton_Clicked(object sender, EventArgs e) { ListView.SwipeItem(viewModel.contactsinfo[1], -150); }
Screenshot