Calling Xamarin Forms ListView Context Action Commands From The Base View-Model

The listview is surely one of the most used Xamarin Forms views. It is flexible and permits users to display complex sets of data easily. It has several builtin functionalities. Some of which are straight forward and easy to implement and others are tricky. There are several advanced functionalities which can be implemented on the xamarin forms’ List view, and I made a blog post about them here. But I decided to make a single more detailed post about this feature.

Here is the source code for this tutorial, you can download and study it as you wish.

How to Call Xamarin Forms ListView Context Action Commands From The View Model

Let me explain one scenario in which this functionality fits in perfectly. Let’s say you have a List View. To each item template’s view cell, you add context actions. Now you want to link the commands of those context actions back to your view model. How do you do that ?. Making it more complex, you have defined each template for that list view in its own unique XAML file. And each of those templates have their context actions. How do you link the commands present on the View Model which the List View is bound, to the context actions of each item template’s view cell ?. This sounds a little bit complex right ?. You could chose the ugly approach of responding to these context actions in code behind and passing the required response or data back to the View Model via an event or even the Xamarin Forms’ messaging center. But NO don’t do that. Instead, respecting the MVVM design pattern is the best way. You do that by calling the xamarin forms context action commands from the view model. This is exactly what we will talk about through out this article.

Implementation

We are going to implement the most complex scenario, where your item templates and in separate XAML files, and you call the commands right from the View Models.

  • First, add a new Bindable property to each of your templates (The View Cells you created as item templates for your list view). This bindable property will serve as a recipient for the binding context of the template’s underlying view. Here is the code for this:
public static readonly BindableProperty BaseContextProperty =
              BindableProperty.Create("BaseContext", typeof(object), typeof(CompletedTodoTemplate), null, propertyChanged: OnParentContextPropertyChanged);

        public object BaseContext
        {
            get { return GetValue(BaseContextProperty); }
            set { SetValue(BaseContextProperty, value); }
        }

private static void OnParentContextPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            if (newValue != oldValue && newValue != null)
            {
                (bindable as CompletedTodoTemplate).BaseContext = newValue;
            }
        }
  • Inside the view cell’s XAML add a name property. This name will be used to reference the View Cell via XAML from the views it contains.
x:Name="Template"
  • While declaring the context menus, bind the command parameter to its self (This will pass the list view’s specific item which is presented by that template back to the view model as a command parameter for that specific command). And the command to the BaseContext’s corresponding command. as follow :
<ViewCell.ContextActions>
       <MenuItem Command="{Binding BaseContext.DeleteTodoCommand, Source={x:Reference Template}}" 
                 CommandParameter="{Binding .}"  x:Name="DeleteMenuItem" Text="Delete"/>
   </ViewCell.ContextActions>
  • Now in the page which contain’s the List View, add a name to that page too.
x:Name="TodoPage"
  • When declaring the Templates in XAML, pass the page’s Binding Context to the template via the bindable property we created earlier called BaseContext. Here is how you do it.
<DataTemplate x:Key="CurrentTodoDataTemplate">
                    <dataTemplates:CurrentTodoTemplate BaseContext="{Binding BindingContext, Source={x:Reference TodoPage}}"/>
                </DataTemplate>

With this, you are done and your context menu actions should easily call their corresponding commands from the view model.

Here is the source code for this tutorial, you can download and study it as you wish.

This Xamarin Forms application to help you manage your expenses and income was built entirely with Xamarin Forms and ReactiveUI. You can download and use it or play with it for free on Android and Windows 10 (Universal Windows Platform). You can get it on Playstore, or on the Microsoft Store

Follow me on social media and stay updated

Demo, Xamarin Forms ListView Context Action Commands From The View Model
Demo, Xamarin Forms ListView Context Action Commands From The View Model

Conclusion

After performing each of these steps, you will able to call a xamarin forms listview context actions from the view model. This method totally respects the MVVM design pattern, so it is advisable to use it. This is a complex scenario, you could easily twist this approach to achieve the same result for simple scenarios. Where for example, the templates are defined inside the list view.

If you liked this post, or it was useful to you, please 👍 like it, share it on twitter, facebook or other social media… in case you want to get updated on any new useful post, follow me on twitter,  Github  and like my page on facebook. And every other social media by clicking on the  buttons at the end of this post.

Follow me on social media and stay updated

Follow me on social media and stay updated

2 Replies to “Calling Xamarin Forms ListView Context Action Commands From The Base View-Model”

  1. That is kind of a long way around, you don’t need any bindable properties. What I do is reference the Page control directly instead of passing through a dummy property.

    Command="{Binding Source={x:Reference LoginPageRoot},
                                       Path=ViewModel.LoginAthleteCommand}"
    CommandParameter="{Binding EnteredPassword}"
    
    1. Don’t get me wrong, your approach seems right, but does it work when you have several view cells defined in different files with their own context actions ?(that is the particular scenario I talk about in this blog post) If it does, please can you share more code demonstrating your approach ? I’ll like to go through it and update this post if necessary.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.