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>
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;
}
Bind to the Opening
event of the MenuFlyout
. In the event handler the sender
is the MenuFlyout
itself. There you will find the Target
property which points to the ListViewItem
.
Based on your example your XAML could look like this:
<ListView ItemsSource="{Binding}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="ContextFlyout">
<Setter.Value>
<MenuFlyout Opening="ListView_Opening">
<MenuFlyoutItem Text="Choice A" Click="ChoiceA_Click" />
<MenuFlyoutItem Text="Choice B" />
</MenuFlyout>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
</ListView>
Your code behind goes like this:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.DataContext = new List<String>{ "Item 1", "Item 2", "Item 3"};
}
private string ListViewItemString;
private void ChoiceA_Click(object sender, RoutedEventArgs e)
{
// What was clicked?
var clickedItem = ListViewItemString;
}
private void ListView_Opening(object sender, object e)
{
ListViewItemString = ((sender as MenuFlyout)?.Target as ListViewItem)?.Content as string;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With