Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the source of a ContextMenu-originated event in WPF?

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?

like image 788
sker Avatar asked Dec 06 '25 15:12

sker


2 Answers

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.

like image 114
Dennis Avatar answered Dec 08 '25 07:12

Dennis


//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?

like image 27
TonyKMN Avatar answered Dec 08 '25 06:12

TonyKMN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!