Data binding to SelectedItem in a WPF Treeview

后端 未结 20 803
南方客
南方客 2020-11-22 05:39

How can I retrieve the item that is selected in a WPF-treeview? I want to do this in XAML, because I want to bind it.

You might think that it is SelectedItem

20条回答
  •  死守一世寂寞
    2020-11-22 06:38

    This can be accomplished in a 'nicer' way using only binding and the GalaSoft MVVM Light library's EventToCommand. In your VM add a command which will be called when the selected item is changed, and initialize the command to perform whatever action is necessary. In this example I used a RelayCommand and will just set the SelectedCluster property.

    public class ViewModel
    {
        public ViewModel()
        {
            SelectedClusterChanged = new RelayCommand( c => SelectedCluster = c );
        }
    
        public RelayCommand SelectedClusterChanged { get; private set; } 
    
        public Cluster SelectedCluster { get; private set; }
    }
    

    Then add the EventToCommand behavior in your xaml. This is really easy using blend.

    
        
            
                
            
        
    
    

提交回复
热议问题