Search code examples
c#wpfmvvmmodeltreeviewitem

How To Access Data of an TreeViewItem Object


I build an MVVM pattern TreeView with

-Root
--Item
---Subitem

When clicking on any of the TreeViewItems, I would like to display the details of the actual Object (Model) in an separate Window.

But I'm not sure how to access the data of the object.

private void TreeView_OnSelectedItemChanged(object sender, RoutedEventArgs e)
{
    TreeViewItem tvi = e.OriginalSource as TreeViewItem;
    MessageBox.Show(tvi.ToString());
}

Solution

  • I would not recommend of using TreeView_OnSelectedItemChanged in MVVM styled WPF applicaiton.

    Define on on your ModelView binded a binding to IsSelected property of TreeeViewItem and you wil be always aware of selection,a nd can select the item of interest from the code, as well.