How to notify item selection using MVVM in .NET MAUI ListView (SfListView)?
The .NET MAUI SfListView allows you to 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:listView="clr-namespace:Syncfusion.Maui.ListView;assembly=Syncfusion.Maui.ListView">
<ContentPage.BindingContext>
<local:ContactsViewModel x:Name="ViewModel"/>
</ContentPage.BindingContext>
<ContentPage.Resources>
<ResourceDictionary>
<local:CustomConverter x:Key="EventArgs" />
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<Grid>
<listView:SfListView x:Name="listView"
ItemsSource="{Binding Items}" >
<listView:SfListView.Behaviors>
<local:EventToCommandBehavior EventName="SelectionChanged"
Command="{Binding SelectionChangedCommand}"
Converter="{StaticResource EventArgs}" />
</listView:SfListView.Behaviors>
<listView:SfListView.ItemTemplate>
<DataTemplate>
<Grid>
<Label Text="{Binding ContactName}" FontSize="Medium" />
</Grid>
</DataTemplate>
</listView:SfListView.ItemTemplate>
</listView:SfListView>
</Grid>
</ContentPage.Content>
</ContentPage>
C#:
namespace ListViewMaui
{
public class ContactsViewModel : INotifyPropertyChanged
{
public Command<object> SelectionChangedCommand
{
get { return selectionChangedCommand; }
protected set { selectionChangedCommand = value; }
}
public ContactsViewModel()
{
selectionChangedCommand = new Command<object>(OnSelectionChanged);
Items = new ObservableCollection<Contacts>();
}
public void OnSelectionChanged(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");
}
}
}
}
}
Output:
Conclusion
I hope you enjoyed learning how to notify item selection using MVVM in .NET MAUI ListView.
You can refer to our .NET MAUI ListView feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our .NET MAUI ListView example to understand how to create and manipulate data.
For current customers, you can 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.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!