Why e.Source depends on TreeView populating method?

后端 未结 2 706
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 11:05

I have two trees:

  1. fooTree - made up of elements,
  2. barTree - constructed by

Both trees have MouseRightButtonDown event, but the e.Sour

相关标签:
2条回答
  • 2021-01-14 11:35

    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...

    0 讨论(0)
  • 2021-01-14 11:38

    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/

    1. 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.

    2. 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.

    3. 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;
    }
    
    0 讨论(0)
提交回复
热议问题