Johnny Johnny - 1 year ago 518
C# Question

How do you use the ContextFlyout with a ListView?

I am trying to add a MenuFlyout to my UWP app for supporting a controller. The problem is that I can't figure out how to determine which ListViewItem actually triggered the event.


public sealed partial class MainPage : Page
public MainPage()

this.DataContext = new List<String>{ "Item 1", "Item 2", "Item 3"};

private void ChoiceA_Click(object sender, RoutedEventArgs e)
// What was clicked?


<ListView ItemsSource="{Binding}">
<Style TargetType="ListViewItem">
<Setter Property="ContextFlyout">
<MenuFlyoutItem Text="Choice A" Click="ChoiceA_Click" />
<MenuFlyoutItem Text="Choice B" />

Answer Source

I just tested your code with Local machine and Mobile emulator, your MenuFlyout can be shown only on PC by right tapped on the ListView, then here is a solution, you can find the OriginalSource in the RightTapped event of ListView, then get the DataContext of this OriginalSource for example like this:

private FrameworkElement originalSource;
private void ChoiceA_Click(object sender, RoutedEventArgs e)
    var itemdatacontext = originalSource.DataContext;

private void ListView_RightTapped(object sender, RightTappedRoutedEventArgs e)
    originalSource = (FrameworkElement)e.OriginalSource;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download