Select TreeView Node on right click before displaying ContextMenu

后端 未结 11 1960
鱼传尺愫
鱼传尺愫 2020-11-29 19:39

I would like to select a WPF TreeView Node on right click, right before the ContextMenu displayed.

For WinForms I could use code like this Find node clicked under co

11条回答
  •  有刺的猬
    2020-11-29 20:09

    If you want a XAML-only solution you can use Blend Interactivity.

    Assume the TreeView is data bound to a hierarchical collection of view-models having a Boolean property IsSelected and a String property Name as well as a collection of child items named Children.

    
      
        
      
      
        
          
            
              
                
              
            
          
        
      
    
    

    There are two interesting parts:

    1. The TreeViewItem.IsSelected property is bound to the IsSelected property on the view-model. Setting the IsSelected property on the view-model to true will select the corresponding node in the tree.

    2. When PreviewMouseRightButtonDown fires on the visual part of the node (in this sample a TextBlock) the IsSelected property on the view-model is set to true. Going back to 1. you can see that the corresponding node that was clicked on in the tree becomes the selected node.

    One way to get Blend Interactivity in your project is to use the NuGet package Unofficial.Blend.Interactivity.

提交回复
热议问题