Hunt
Hunt

Reputation: 8435

ListView ItemTapEvent using MVVMLight

I am trying to build an application using Xamarin Forms and MVVMLight. I have created master detail page with the menu items. when user taps on the menu item i want to navigate the page. Now the problem is to create the ItemTapped event for ListView using MVVMLight i tried to find over web but could not get the proper answer that really works.

so far i tried to implement EventToCommand using MVVMLight but xaml is throwing error by saying

The attachable property Behaviors was not found in type Interaction

<ListView 
            ItemsSource="{Binding MenuItemsList}"            
            CachingStrategy="RecycleElement"           
            Margin="0,0,0,10"
            RowHeight="110"
            SeparatorVisibility="Default"
            x:Name="MenuList"

            >
            <i:Interaction.Behaviors>
                <i:BehaviorCollection>
                    <cmd:EventToCommand EventName="ItemSelected" Command="{Binding OnTapCommand}"                                   
                </i:BehaviorCollection>
            </i:Interaction.Behaviors>
              <DataTemplate>
                    <ViewCell>
                    </ViewCell>
              </DataTemplate>
</ListView>

namespaces that i am using are mentioned below

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"

when i was not using MVVMLight i used to use custom behavior such as behaviors:ItemTappedCommandBehavior.ItemTappedCommand="{Binding OnContactSelectCommand}"

but i really don't know how to do the same with the MVVMLight. I am trying to run the mobile app on android and iOS platform

Upvotes: 0

Views: 115

Answers (1)

Depechie
Depechie

Reputation: 6142

When showing items in a ListView for a menu, you can just leverage the build in functionality of a ListView to know what the user 'selected'.

In other words, just bind the SelectedItem property of the ListView to a property in your VM. In that property setter you can code your logic to trigger the correct page navigation.

So the XAML should look like:

<ListView ItemsSource="{Binding MenuItemsList}"
          CachingStrategy="RecycleElement"
          Margin="0,0,0,10"
          RowHeight="110"
          SeparatorVisibility="Default"
          x:Name="MenuList"
          SelectedItem="{Binding SelectedMenuItem}">
    <DataTemplate>
        <ViewCell>
        </ViewCell>
    </DataTemplate>
</ListView>

Upvotes: 1

Related Questions