WPF: TreeViewItem bound to an ICommand

后端 未结 6 760
离开以前
离开以前 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条回答
  •  Happy的楠姐
    2021-02-08 19:39

    Thanks for the input into the issue, and yes, I did say I didn't want a Code behind solution, however at that time I was still very much under the impression that I was simply missing something... so I ended up using the TreeView_SelectedItemChanged event.

    Even though Will's approach seems like a good work around, for my personal situation I decided that I would use the code behind. The reason for this is so that the View and XAML would remain as it would be if the TreeViewItem had a "Command" property to which my Command could be bound. Now I do not have to change the Templates or the Views, all I have to do is add the code and the Event for the TreeView_SelectedItemChanged.

    My solution:

      private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs e)
        {
            if (sender != null)
            {
                var treeView = sender as TreeView;
                if (treeView != null)
                {
                    var commandViewModel = treeView.SelectedItem as CommandViewModel;
                    if (commandViewModel != null)
                    {
                        var mi = commandViewModel.Command.GetType().GetMethod("Execute");
                        mi.Invoke(commandViewModel.Command, new Object[] {null});
                    }
                }
            }
        }
    
    
    

    As I already have the RelayCommand attached to the TreeViewItem, all I am now doing is to just manually invoke the "Execute" method on that specific RelayCommand.

    If this is the completely wrong way of going about it then please let me know...

    Thanks!

    提交回复
    热议问题