简体   繁体   English

如何访问TreeViewItem对象的数据

[英]How To Access Data of an TreeViewItem Object

I build an MVVM pattern TreeView with 我建立了一个MVVM模式TreeView

-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. 当单击任何TreeViewItem时,我想在单独的窗口中显示实际对象(模型)的详细信息。

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());
}

I would not recommend of using TreeView_OnSelectedItemChanged in MVVM styled WPF applicaiton. 我不建议在MVVM样式的WPF应用程序中使用TreeView_OnSelectedItemChanged

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. 定义对您的ModelView绑定绑定到IsSelected的财产TreeeViewItem你时便会随时了解选择的,一个第二可以选择从代码感兴趣的项目,以及。

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. 由于您希望通过显示TreeViewItem绑定对象的详细信息来对TreeView中的选择更改做出反应,因此可以使用Caliburn MicroAction机制。 You can hook up the SelectedItemChanged event of your TreeView to a method in your ViewModel. 您可以将TreeView的SelectedItemChanged事件连接到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: 在ViewModel中,您将具有以下方法:

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

If you have problems setting this up let me know. 如果您在设置时遇到问题,请告诉我。

在ViewModel中,创建TreeViewItem类型的依赖项属性,然后在View中将TreeView的SelectedValuePath属性绑定到新的依赖项属性。

在MVVM模式中,与控件关联的数据应位于DataContext依赖项属性中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM