Search code examples
mvvmxamarin.formsfreshmvvm

Listen to ItemTapped Event in FreshMvvm


In my project I have a list view, now listening to SelectedItem change is easy, every tutorial has that, but I can't find anything on using ItemTapped event.

What do I bind the event to in the modelPage?

Thanks,

Mike


Solution

  • Since ItemTapped is an event and not a Command (or BindableProperty at all) you cannot use it directly from you PageModel.

    They have invented something like Behaviors for this. With Behaviors you can turn an Event to a Command.

    While there are third party plugins which do this like Corcav's one, it is also built into Xamarin.Forms now.

    Let me explain it by the Corcav one, other implementations should be similar. Also I'm assuming you're using XAML.

    First of all, install the NuGet and don't forget to include the right namespace into your page, which means adding something like: xmlns:behaviors="clr-namespace:Corcav.Behaviors;assembly=Corcav.Behaviors"

    Now under your ListView declare your Behaviors like so:

    <!-- ... more XAML here ... -->
    <ListView IsPullToRefreshEnabled="true" RefreshCommand="{Binding RefreshDataCommand}" IsRefreshing="{Binding IsBusy}"  IsVisible="{Binding HasItems}" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" CachingStrategy="RecycleElement">
            <behaviors:Interaction.Behaviors>
              <behaviors:BehaviorCollection>
                <behaviors:EventToCommand EventName="ItemSelected" Command="{Binding ItemSelectedCommand}" />
              </behaviors:BehaviorCollection>
            </behaviors:Interaction.Behaviors>
    
    <!-- ... more XAML here ... -->
    

    Note that is is a collection, so you could add more if you want (also in other scenarios). Also note that I did in fact user the SelectedItem as well. This is probably what you want because else the item you tapped will stay selected. So the SelectedItem property doesn't do much more than set it back to null (hence the TwoWay). But you can also take the actual selected item from there.

    So now in your PageModel declare a Command and assign it with something like this:

    private void ItemSelected()
    {
        // Open the article page.
        if (_selectedItem != null)
        {
            CoreMethods.PushPageModel<GroupArticlePageModel>(_selectedItem, false, true);
        }
     }
    

    _selectedItem being the property to which the tapped item is assigned. Of course you could do it even better and supply the behavior with a CommandParameter in which you put the tapped item reference.