WPF: TreeViewItem bound to an ICommand

后端 未结 6 632
离开以前
离开以前 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:52

    The answer provided by Shaggy13spe is very good. But still, it took me some additional time to understand it so I will extend the answer.

    Whole TreeView xaml can look like this:

    
        
            
                
            
        
        
            
                
                    
                    
                
            
        
    
    

    In my View I have a Tree collection

    public ObservableCollection Tree { get; set; }
    

    TreeNode is defined as a simple class:

    public class TreeNode
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List Nodes { get; set; }
    
        public TreeNode(string name)
        {
            this.Name = name;
            this.Nodes = new List();
        }
    }
    

    First important point: CommandParameter is not bind to the property on the ViewModel but it is passed to the method. So the method should look like:

    private async void FilterMeeting(object parameter){}
    

    Second important point: if you will pass the selected item (in my case object will be TreeNode type) and you will have the hierarchical structure you will face event bubbling. So selecting an item will fire the event for this particular item and for all parents. To resolve this you need to understand that you can pass only one object to the method in ViewModel (not two as in standard event handler) and this object needs to be an event.

    In this case change the XAML to following (PassEventArgsToCommand="True" is important here)

    
        
            
                
            
        
        
            
                
                    
                    
                
            
        
    
    

    Then in your handling method, you won't receive the model object, but event args, which have a model object inside.

提交回复
热议问题