Data binding to SelectedItem in a WPF Treeview

后端 未结 20 1191
南方客
南方客 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条回答
  •  猫巷女王i
    2020-11-22 06:31

    It can also be done using the IsSelected property of the TreeView item. Here's how I managed it,

    public delegate void TreeviewItemSelectedHandler(TreeViewItem item);
    public class TreeViewItem
    {      
      public static event TreeviewItemSelectedHandler OnItemSelected = delegate { };
      public bool IsSelected 
      {
        get { return isSelected; }
        set 
        { 
          isSelected = value;
          if (value)
            OnItemSelected(this);
        }
      }
    }
    

    Then in the ViewModel that contains the data your TreeView is bound to, just subscribe to the event in the TreeViewItem class.

    TreeViewItem.OnItemSelected += TreeViewItemSelected;
    

    And finally, implement this handler in the same ViewModel,

    private void TreeViewItemSelected(TreeViewItem item)
    {
      //Do something
    }
    

    And the binding of course,

        
    

提交回复
热议问题