WPF: TreeViewItem bound to an ICommand

后端 未结 6 638
离开以前
离开以前 2021-02-08 19:24

I am busy creating my first MVVM application in WPF.

Basically the problem I am having is that I have a TreeView (System.Windows.Controls.TreeView) which I have placed

6条回答
  •  无人共我
    2021-02-08 19:30

    I improve good solution from Richard via common Tag property:

    MyView.xaml:

     
                      
                      
                          
                      
                  
    

    MyView.xaml.cs

        private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs e)
        {
            var treeView = (TreeView)sender;
            var command = (ICommand)treeView.Tag;
            TreeViewItem selectedItem = (TreeViewItem)treeView.SelectedItem;
            if (selectedItem.Tag != null)
            {
                command.Execute(selectedItem.Tag);
            }
        }
    
    
    

    MyViewModel.cs

          public RelayCommand selectTreeViewCommand;
          [Bindable(true)]
          public RelayCommand SelectTreeViewCommand => selectTreeViewCommand ?? (selectTreeViewCommand = new RelayCommand(CanSelectTreeViewCommand, ExecuteSelectTreeViewCommand));
    
          private void ExecuteSelectTreeViewCommand(object obj)
          {
              Console.WriteLine(obj);
          }
    
          private bool CanSelectTreeViewCommand(object obj)
          {
              return true;
          }
    

    提交回复
    热议问题