0

I have implemented the SelectedItem of a treeview according to the following article: Data binding to SelectedItem in a WPF Treeview

The SelectedItem works perfect and it truly reflects the item selected.

Now I want to interact with the selected item, but I'm not sure how. I can create an instance of the BindableSelectedItemBehavior class, but this is not the instance containing the data I'm looking for. How to access the class instance holding the SelectedItem of the treeview?
This is a highlight of my code:

namespace QuickSlide_2._0
{
  public class BindableSelectedItemBehavior : Behavior<TreeView>
  {
  ...
  }

  public partial class Window1 : Window
  {
  .....
    private void New_subject_Click(object sender, RoutedEventArgs e)
    {
    // here the code to read the instance of the class BindableSelectedItemBehavior and interact  
    // with the selectedItem when I click on the button
    }
  }
}

Maybe I'm looking totally in the wrong direction. Your help would be highly appreciated!

Community
  • 1
  • 1

1 Answers1

0

You want to use MVVM so that you can bind the dependency property of your behavior and then you can access the value of the SelectedItem that you made.

public class BindableSelectedItemBehavior : Behavior<TreeView>
{
     //Dependency property called SelectedTreeViewItem register it
}

public partial class Window1 : Window
{
     public Window1()
     {
       DataContext = new WindowViewModel();
     }

    private void New_subject_Click(object sender, RoutedEventArgs e)
    {
    // here the code to read the instance of the class BindableSelectedItemBehavior and interact  
    // with the selectedItem when I click on the button
       var windowViewModel = DataContext as WindowViewModel;
       var selectedItem = windowViewModel.SelectedItem;
    }
}

public class WindowViewModel()
{
      public object SelectedItem { get; set; } // You want to change object to the type you are expecting
}

and on your View

<TreeView>
  <TreeView.Behaviors>
       <BindableSelectedItemBehavior SelectedTreeViewItem="{Binding SelectedTreeViewItem,Mode=TwoWay}">
  </...>
</...>
123 456 789 0
  • 10,565
  • 4
  • 43
  • 72