Tatyana Olshevskaya
Tatyana Olshevskaya

Reputation: 43

Best practice to handle ListView ItemClick in UWP using MVVM

I need to open a new view (item details) on mouse double click in ListView in UWP using MVVM. In WPF I used a command with a parameter and EventTrigger but Microsoft does not recommended to use it in UWP:

Triggers, EventTrigger, Actions and BeginStoryboard are not commonly used. These API mainly exist for compatibility in XAML originally used for Microsoft Silverlight...For events in control templates, use visual states and VisualStateManager.

As I understood it is used when you need to change visual state of the control but I need to open a new view.
How can I use VisualStateManager for my purpose?

There is how my XAML looked in WPF:

<ListBox x:Name="PersonsListControl" Grid.RowSpan="3" Grid.Row="0" Grid.Column="2" 
         ItemsSource="{Binding Path=PersonsProvider}" 
         ItemsPanel="{StaticResource PersonsListPanelTemplate}"
         ItemTemplate="{StaticResource PersonsListItemTemplate}"
         SelectedItem="{Binding SelectedPerson}"
         ScrollViewer.HorizontalScrollBarVisibility="Disabled">

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseDoubleClick">
            <i:InvokeCommandAction
                Command="{Binding GetPersonDetailsCommand}"
                CommandParameter="{Binding SelectedPerson}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>

</ListBox>

Upvotes: 2

Views: 2731

Answers (1)

mrogal.ski
mrogal.ski

Reputation: 5930

In UWP you can use {x:Bind ...} :

<ListBox ...
         DoubleTapped="{x:Bind HandleDoubleTapped}" />

And in your ViewModel just create a method :

public void HandleDoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
{
    // your logic
}

References :
DoubleTapped
ListBox


EDIT:
@JörgenSigvardsson pointed out that x:Bind do not bind directly to the DataContext and you should create a proxy property/properties to access particular data from your page.
More on that can be read here

Upvotes: 3

Related Questions