I have two trees:
Both trees have MouseRightButtonDown event, but the e.Sour
You can get the clicked item in the bartree using:
((e.Source) as TreeView).SelectedValue
But be aware that the item must actually selected first (using leftMouse). The item is not immediately selected using rightMouse...
Don't know why this happens, but at least I have found a solution:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/f0d3af69-6ecc-4ddb-9526-588b72d5196b/
If your handler is on the TreeView, use the OriginalSource property in the event arguments and walk up the visual parent chain until you find a TreeViewItem. Then, select it. You can walk the visual parent chain by using System.Windows.Media.VisualTreeHelper.GetParent.
You could try registering a class handler for type TreeViewItem and the mouse down event. Then, your handler should only be called when mouse events pass through TreeViewItem elements.
You could register a class handler for type TreeViewItem and the context menu opening event.
So my code is:
private void OnMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
TreeViewItem treeViewItem = VisualUpwardSearch<TreeViewItem>(e.OriginalSource as DependencyObject) as TreeViewItem;
}
static DependencyObject VisualUpwardSearch<T>(DependencyObject source)
{
while (source != null && source.GetType() != typeof(T))
source = VisualTreeHelper.GetParent(source);
return source;
}