Data binding to SelectedItem in a WPF Treeview

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

    I know this thread is 10 years old but the problem still exists....

    The original question was 'to retrieve' the selected item. I also needed to "get" the selected item in my viewmodel (not set it). Of all the answers in this thread, the one by 'Wes' is the only one that approaches the problem differently: If you can use the 'Selected Item' as a target for databinding use it as a source for databinding. Wes did it to another view property, I will do it to a viewmodel property:

    We need two things:

    • Create a dependency property in the viewmodel (in my case of type 'MyObject' as my treeview is bound to object of the 'MyObject' type)
    • Bind from the Treeview.SelectedItem to this property in the View's constructor (yes that is code behind but, it's likely that you will init your datacontext there as well)

    Viewmodel:

    public static readonly DependencyProperty SelectedTreeViewItemProperty = DependencyProperty.Register("SelectedTreeViewItem", typeof(MyObject), typeof(MyViewModel), new PropertyMetadata(OnSelectedTreeViewItemChanged));
    
        private static void OnSelectedTreeViewItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as MyViewModel).OnSelectedTreeViewItemChanged(e);
        }
    
        private void OnSelectedTreeViewItemChanged(DependencyPropertyChangedEventArgs e)
        {
            //do your stuff here
        }
    
        public MyObject SelectedWorkOrderTreeViewItem
        {
            get { return (MyObject)GetValue(SelectedTreeViewItemProperty); }
            set { SetValue(SelectedTreeViewItemProperty, value); }
        }
    

    View constructor:

    Binding binding = new Binding("SelectedItem")
            {
                Source = treeView, //name of tree view in xaml
                Mode = BindingMode.OneWay
            };
    
            BindingOperations.SetBinding(DataContext, MyViewModel.SelectedTreeViewItemProperty, binding);
    

提交回复
热议问题