How to pass the item data as command parameter in ItemTapped command in .NET MAUI ListView?
In .NET MAUI ListView(SfListView), DataItem can only be passed to the view model instead of EvenArgs using EventsToCommand behavior to follow the MVVM pattern.
To achieve this, create a command to the ItemTapped event of SfListView in ViewModel.
C#
public class ContactsViewModel
{
Command<object> tapCommand;
public Command<object> TapCommand
{
get { return tapCommand; }
protected set { tapCommand = value; }
}
public ContactsViewModel()
{
tapCommand = new Command<object>(OnTapped);
}
public void OnTapped(object obj)
{
var name = (obj as Contacts).ContactName ;
var alert = Application.Current.MainPage.DisplayAlert("Parameter Passed","Name:" + name,"Cancel");
}
}
Associate that command to the appropriate event of SfListView using behaviors.
Xaml
<listView:SfListView x:Name="listView">
<listView:SfListView.Behaviors>
<local:EventToCommandBehavior EventName="ItemTapped"
Command="{Binding TapCommand}"
Converter="{StaticResource EventArgs}" />
</listView:SfListView.Behaviors>
</listView:SfListView>
Here, CustomConverter returns ItemData from ItemTappedEventArgs.
C#
public class CustomConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
object eventArgs = null;
Syncfusion.Maui.ListView.ItemTappedEventArgs eventArg = null;
if (value is Syncfusion.ListView.XForms.ItemTappedEventArgs)
{
eventArg = value as Syncfusion.Maui.ListView.ItemTappedEventArgs;
eventArgs = eventArg.DataItem;
}
return eventArgs;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
When tapping the ListViewItem, ItemData will only be returned from Customconverter to the command in ViewModel and performed the desired operation.
Output Screenshot
Conclusion:
I hope you enjoyed learning about how to pass the item data as command parameter in ItemTapped command.
You can refer to our .NET MAUI SfListView feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications.
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!