Articles in this section
Category / Section

How to convert events into commands in .NET MAUI ListView (SfListView)?

2 mins read

The .NET MAUI ListView allows you to convert the events into commands using Behaviors to follow the MVVM pattern.

C#
To achieve this, need to create a command for the ItemTapped event of the SfListView in the ViewModel.

public class ContactsViewModel : INotifyPropertyChanged
{
    #region Properties

    public Command<Syncfusion.Maui.ListView.ItemTappedEventArgs> tapCommand;

    public Command<Syncfusion.Maui.ListView.ItemTappedEventArgs> TapCommand
    {
        get { return tapCommand; }
        set { tapCommand = value; OnPropertyChanged("TapCommand"); }
    }

    #endregion

    #region Constructor

    public ContactsViewModel()
    {
       TapCommand = new Command<Syncfusion.Maui.ListView.ItemTappedEventArgs>(OnTapCommand);
    }

    private void OnTapCommand(Syncfusion.Maui.ListView.ItemTappedEventArgs obj)
    {
        var name = (obj.DataItem as Contacts).ContactName;
        var number = (obj.DataItem as Contacts).ContactNumber;
        App.Current.MainPage.DisplayAlert(name, "Number:" + number, "Ok");
    }

XAML

Associate the command to the appropriate event of SfListView using Behaviors, as shown below.

<syncfusion:SfListView x:Name="listView" >
 <syncfusion:SfListView.Behaviors>
   <local:EventToCommandBehavior EventName="ItemTapped"
                                 Command="{Binding TapCommand}">
   </local:EventToCommandBehavior>
 </syncfusion:SfListView.Behaviors>
</syncfusion:SfListView>

Now, when an item in the ListView is tapped, the corresponding Command in the ViewModel will be invoked automatically, performing the desired operation, as illustrated in the screenshot.

Output

How to turn events into commands

Download the complete sample from GitHub.

Conclusion:

I hope you enjoyed learning how to convert events into commands in .NET MAUI ListView (SfListView).

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 with configuration specifications.

Check out our components from the License and Downloads page for current customers. If you are new to Syncfusion®, try our 30-day free trial to check out our other controls.

Please let us know in the comments section if you have any queries or require clarification. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

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