Frage

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());
}
War es hilfreich?

Lösung

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.

Andere Tipps

My prior answer was addressing more than what was asked.

Since you want to react on selection changing in the TreeView by displaying the details of the TreeViewItem's bound object, you could use Caliburn Micro's Action mechanism. You can hook up the SelectedItemChanged event of your TreeView to a method in your ViewModel.

For Example in your View:

<TreeView 
    ItemsSource="{Binding YourDataObjects}"
    cal:Message.Attach="[Event SelectedItemChanged] = [Action OnSelectedItemChanged($this)]"/>

And in your ViewModel you will have this method:

public void OnSelectedItemChanged(YourDataObject selectedItem)
{
    //Do something with the selected item here 
}

If you have problems setting this up let me know.

In an MVVM pattern, the data associated to a a control is supposed to be in the DataContext dependency property.

In your ViewModel, create a dependency property of type TreeViewItem, and in the View bind the SelectedValuePath property of the TreeView to your new dependency property.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top