rhcpfan
rhcpfan

Reputation: 567

Get ClickedItem from a ListView (using MVVM)

I have a ListView in a Windows Universal Application, described as follows:

ListView ItemsSource="{Binding RecentlyAddedTvSeriesEpisodes}"
         IsItemClickEnabled="True" SelectionMode="Single"
         x:Name="listOfThings">

         <!--Behaviour for item click-->
         <i:Interaction.Behaviors>
             <core:EventTriggerBehavior EventName="ItemClick">
                 <core:InvokeCommandAction Command="{Binding VideoItemClickCommand}" 
             CommandParameter="{Binding ElementName=listOfThings, Path=SelectedItem}"/>
             </core:EventTriggerBehavior>
         </i:Interaction.Behaviors>                   

         <!--ListView template for all items-->
         <ListView.ItemTemplate>
             <DataTemplate>
             ...
             </DataTemplate>
         </ListView.ItemTemplate>
</ListView>

If I click on an item, the behaviour is to invoke a relay command and pass as a CommandParameter the SelectedItem property of the ListView.

If no item is selected in the ListView, it passes the ItemClickEventArgs object. From this, I can easily get the clicked item:

private async void ExecuteItemClickCommand(ItemClickEventArgs parameter)
{
    //Get the clicked item
    Model.VideoModel selectedVideo = parameter.ClickedItem as VideoModel;
}

If an item is selected in the ListView, it passes to the RelayCommand the SelectedItem property (directly the model) even if I click on other item rather than the selected one.

I would like to find out how to get the ClikedItem of a ListView, regardless the selected items in the ListView

Upvotes: 1

Views: 186

Answers (1)

Filip Skakun
Filip Skakun

Reputation: 31724

I'm not sure how to get it through the behavior, but how about simply handling the event in code behind and invoking the command from there? You'll probably save 3 lines of code and a a few kBs of binary size...

Upvotes: 1

Related Questions