WPF selection of a TreeView item as context menu is called

前端 未结 3 1373
别那么骄傲
别那么骄傲 2020-12-21 11:06

This problem relates mainly to context menus, but in my specific case it\'s about a TreeView control.

The TreeView item contains a StackPanel, and on that StackPanel

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-21 11:48

    You could add an IsSelected property to your SceneViewModel and CharacterViewModel classes and bind the IsSelected of the TreeViewItem to these properties using a style. In the same style you could then hook up an event handler for the PreviewMouseRightButtonDown to set the source property:

    
        
            
        
    
    

    private void treeView_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        TreeViewItem tvi = sender as TreeViewItem;
        CharacterViewModel cvm = tvi.DataContext as CharacterViewModel;
        if (cvm != null)
        {
            cvm.IsSelected = true;
        }
        else
        {
            SceneViewModel svm = tvi.DataContext as SceneViewModel;
            if (svm != null)
                svm.IsSelected = true;
        }
    }
    

    Make sure that the CharacterViewModel and SceneViewModel classes implement the INotifyPropertyChanged interface and raise the PropertyChanged event in the setter of the new IsSelected property.

提交回复
热议问题