Data binding to SelectedItem in a WPF Treeview

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

    (Let's just all agree that TreeView is obviously busted in respect to this problem. Binding to SelectedItem would have been obvious. Sigh)

    I needed the solution to interact properly with the IsSelected property of TreeViewItem, so here's how I did it:

    // the Type CustomThing needs to implement IsSelected with notification
    // for this to work.
    public class CustomTreeView : TreeView
    {
        public CustomThing SelectedCustomThing
        {
            get
            {
                return (CustomThing)GetValue(SelectedNode_Property);
            }
            set
            {
                SetValue(SelectedNode_Property, value);
                if(value != null) value.IsSelected = true;
            }
        }
    
        public static DependencyProperty SelectedNode_Property =
            DependencyProperty.Register(
                "SelectedCustomThing",
                typeof(CustomThing),
                typeof(CustomTreeView),
                new FrameworkPropertyMetadata(
                    null,
                    FrameworkPropertyMetadataOptions.None,
                    SelectedNodeChanged));
    
        public CustomTreeView(): base()
        {
            this.SelectedItemChanged += new RoutedPropertyChangedEventHandler(SelectedItemChanged_CustomHandler);
        }
    
        void SelectedItemChanged_CustomHandler(object sender, RoutedPropertyChangedEventArgs e)
        {
            SetValue(SelectedNode_Property, SelectedItem);
        }
    
        private static void SelectedNodeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var treeView = d as CustomTreeView;
            var newNode = e.NewValue as CustomThing;
    
            treeView.SelectedCustomThing = (CustomThing)e.NewValue;
        }
    }
    
    
    

    With this XAML:

    
        
            
        
    
    

    提交回复
    热议问题