Category / Section
How to notify item selection using MVVM in Xamarin.Forms ListView?
1 min read
In Xamarin. Forms ListView, you can find whether the item is selected or not by maintaining bool property in model class. The property value will be updated using selection events like SelectionChanging, SelectionChanged.
Xaml
<ContentPage xmlns:syncfusion="clr-namespace:Syncfusion.ListView.XForms;assembly=Syncfusion.SfListView.XForms" > <ContentPage.Resources> <ResourceDictionary> <local:CustomConverter x:Key="EventArgs" /> </ResourceDictionary> </ContentPage.Resources> <ContentPage.Content> <Grid> <syncfusion:SfListView x:Name="listView" ItemsSource="{Binding contactsinfo}"> <listView:SfListView.Behaviors> <local:EventToCommandBehavior EventName="SelectionChanged" Command="{Binding OnSelectionChangedCommand}" Converter="{StaticResource EventArgs}" /> </listView:SfListView.Behaviors> </syncfusion:SfListView> </Grid> </ContentPage.Content> </ContentPage>
C#
public Command<object> SelectionChangedCommand { get { return selectionChangedCommand; } protected set { selectionChangedCommand = value; } } public ContactsViewModel() { selectionChangedCommand = new Command<object>(OnSelectionChangedCommand); contactsinfo = new ObservableCollection<Contacts>(); } public void OnSelectionChangedCommand (object obj) { var eventArgs = obj as ItemSelectionChangedEventArgs; for (int i = 0; i < eventArgs.RemovedItems.Count; i++) { var item = eventArgs.RemovedItems[i] as Contacts; if (item.IsSelected) { item.IsSelected = false; App.Current.MainPage.DisplayAlert("Message", "Item removed from selected item", "ok"); } } for (int i = 0; i < eventArgs.AddedItems.Count; i++) { var item = eventArgs.AddedItems[i] as Contacts; if (!item.IsSelected) { item.IsSelected = true; App.Current.MainPage.DisplayAlert("Message", "Item added into selected item", "ok"); } } }
Screenshots :
Sample Link : Notify selection using MVVM