Data binding to SelectedItem in a WPF Treeview

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

    I propose this solution (which I consider the easiest and memory leaks free) which works perfectly for updating the ViewModel's selected item from the View's selected item.

    Please note that changing the selected item from the ViewModel won't update the selected item of the View.

    public class TreeViewEx : TreeView
    {
        public static readonly DependencyProperty SelectedItemExProperty = DependencyProperty.Register("SelectedItemEx", typeof(object), typeof(TreeViewEx), new FrameworkPropertyMetadata(default(object))
        {
            BindsTwoWayByDefault = true // Required in order to avoid setting the "BindingMode" from the XAML
        });
    
        public object SelectedItemEx
        {
            get => GetValue(SelectedItemExProperty);
            set => SetValue(SelectedItemExProperty, value);
        }
    
        protected override void OnSelectedItemChanged(RoutedPropertyChangedEventArgs e)
        {
            SelectedItemEx = e.NewValue;
        }
    }
    
    
    

    XAML usage

    
    

    提交回复
    热议问题