Select TreeView Node on right click before displaying ContextMenu

后端 未结 11 2028
鱼传尺愫
鱼传尺愫 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:21

    If you want to stay within the MVVM pattern you could do the following:

    View:

    
        
            
                
            
        
    
    

    Code Behind:

    private void TreeView_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (sender is TextBlock tb && tb.DataContext is YourTreeElementClass te)
        {
            trvName.Tag = te;
        }
    }
    

    ViewModel:

    private YourTreeElementClass _clickedTreeElement;
    
    public YourTreeElementClass ClickedTreeElement
    {
        get => _clickedTreeElement;
        set => SetProperty(ref _clickedTreeElement, value);
    }
    

    Now you could either react to the ClickedTreeElement property change or you could use a command which internally works with the ClickedTreeElement.

    Extended View:

    
        
            
                
                    
                
            
            
                
                    
                
            
        
    
    

提交回复
热议问题