Reputation: 122610
I have the following context menu:
<ListBox x:Name="sectionList" Margin="56,8,15,0" FontSize="64" SelectionChanged="SectionList_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="Hide this section from this list" Click="ContextMenuItem_Click" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<TextBlock Text="{Binding DisplayName}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
As you can see, each displayed item has its own context menu. Each context menu is hooked up to the same event handler:
private void ContextMenuItem_Click(object sender, RoutedEventArgs e)
{
}
From this method, how can I tell which context menu was clicked? I want to know what the DataContext
for the corresponding DataTemplate
is.
Upvotes: 0
Views: 1039
Reputation: 65586
You can get the item the ListBoxItem is bound to by casting the sender as a FrameworkElement
to get access to the DataContext
:
(sender as FrameworkElement).DataContext
You can then cast this to the appropriate model class and access the details you need. e.g.:
((sender as FrameworkElement).DataContext as ItemViewModel).DisplayName
Upvotes: 4
Reputation: 4384
If you use <StackPanel Tag="{Binding}">
then ((FrameworkElement)sender).Tag
will return the DataContext object (you'll have to cast it before use, of course).
Upvotes: 1
Reputation: 32851
If you put a breakpoint inside the event handler ContextMenuItem_Click,
you will then be able to examine the properties of sender
and e
. You will probably find your answer there.
One way to do this is to hover over those words. Another would be to use the Immediate Window. Type in sender
and a dot to get intellisense.
Upvotes: 1