Data binding to SelectedItem in a WPF Treeview

后端 未结 20 1142
南方客
南方客 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:13

    WPF MVVM TreeView SelectedItem

    ... is a better answer, but does not mention a way to get/set the SelectedItem in the ViewModel.

    1. Add a IsSelected boolean property to your ItemViewModel, and bind to it in a Style Setter for the TreeViewItem.
    2. Add a SelectedItem property to your ViewModel used as the DataContext for the TreeView. This is the missing piece in the solution above.
        ' ItemVM...
        Public Property IsSelected As Boolean
            Get
                Return _func.SelectedNode Is Me
            End Get
            Set(value As Boolean)
                If IsSelected  value Then
                    _func.SelectedNode = If(value, Me, Nothing)
                End If
                RaisePropertyChange()
            End Set
        End Property
        ' TreeVM...
        Public Property SelectedItem As ItemVM
            Get
                Return _selectedItem
            End Get
            Set(value As ItemVM)
                If _selectedItem Is value Then
                    Return
                End If
                Dim prev = _selectedItem
                _selectedItem = value
                If prev IsNot Nothing Then
                    prev.IsSelected = False
                End If
                If _selectedItem IsNot Nothing Then
                    _selectedItem.IsSelected = True
                End If
            End Set
        End Property
    
    
        
            
        
        
            
                
            
        
    
    

提交回复
热议问题