Johnny Johnny - 3 months ago 95
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.

CodeBehind

public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();

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

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


XAML

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

Answer

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;
}