views:

477

answers:

3

Hi

I have a TreeView with a ContextMenu with Click events. When the click event in the context menu fires, I get the MenuItem as the source of the event, obviously. How can I get which node in the TreeView was the one who triggered the ContextMenu?

+1  A: 

Generally you store the TreeView node (e.g. the source of the pop-up event, maybe the selected node - depends on your interface to some degree) in a private class-level variable in the ContextMenu's "pop-up" event, then refer to that variable in the menu's click event.

dommer
That's a good idea. Do you know if the popup event is ContextMenuOpening? Because neither ContextMenuOpening nor ContextMenuClosing are firing when I open the menu.
sker
Should be the Opened event. http://msdn.microsoft.com/en-us/library/system.windows.controls.contextmenu.opened.aspx
dommer
Ok, I'm using telerik's treeview and it doesn't have an Opened event, but I managed to do it with the MouseRightButtonUp event. Thank you.
sker
Oops, I was trying to use the Opened event in the TreeView rather than the ContextMenu. I'll use it in the ContextMenu now.
sker
+2  A: 

Alternatively, if you are using RoutedUICommands you can use the OriginalSource property on ExecuteRoutedEventArgs and CanExecuteRoutedEventArgs to find the FrameworkElement where Command started its bubble.

The OriginalSource however maybe the inner TextBlock, or other element in the node's DataTemplate, so you will need to use the VisualTreeHelper to find the parent you want. I have implemented a wrapper around this functionality that is similar to: http://www.hardcodet.net/2008/02/find-wpf-parent/

This approach is good if you want to separate/centralise your command logic in a large application.

Dennis Roche
I've had very good luck using the DataContext property on the OriginalSource when going all-the-way with data binding. OriginalSource should always be a FrameworkElement.
Greg D
My problem is solved for now but your solution seems pretty good. I'll check it out in the next few days. Thank you.
sker
A: 

//there has got to be a better way than this... TreeViewItem tvi = (((sender as MenuItem).Parent as ContextMenu).Parent as Popup).PlacementTarget as TreeViewItem;

This works, but why SHOULDN'T I do it this way?

TonyKMN