如何将此数据绑定到 DataGrid?
我有一个 TreeView
,每个 TreeViewNode
的 Tag
属性中都有一个对象。当选择树视图中的节点时,我希望用通过反射获得的对象所有字段的名称和值填充 DataGrid
。我不知道如何使用 wpf 数据绑定来做到这一点。关于如何使用简单方法准确绑定 DataGrid
的示例非常少,我也使用了转换函数。
到目前为止,我得到的是一种从单个对象获取我想要的数据的方法:
internal static IEnumerable<Tuple<string, object>> GetFieldInfo(object o)
{
return
from FieldInfo info in o.GetType().GetFields()
select Tuple.Create(info.Name, info.GetValue(o));
}
以及 xaml 中的树视图和数据网格:
<TreeView Name="objectList" />
<DataGrid Name="objectData" />
我无法找出正确的 DataBinding 咒语来获取 ((TreeViewNode)objectList .SelectedItem).Tag
属性通过 GetFieldInfo
方法传入 objectData.ItemsSource
属性。
I've got a TreeView
, and each TreeViewNode
has an object in its Tag
property. When a node in the treeview is selected, I want a DataGrid
to be populated with the name and value of all the fields of the object, obtained through reflection. I can't figure out how to do this using wpf databinding. There are very few examples of how exactly you bind a DataGrid
using simple methods, and I'm using a conversion function as well.
What I've got so far is a method to get the data I want from a single object:
internal static IEnumerable<Tuple<string, object>> GetFieldInfo(object o)
{
return
from FieldInfo info in o.GetType().GetFields()
select Tuple.Create(info.Name, info.GetValue(o));
}
and the treeview and datagrid in xaml:
<TreeView Name="objectList" />
<DataGrid Name="objectData" />
I can't figure out the right DataBinding incantations to get the ((TreeViewNode)objectList.SelectedItem).Tag
property through the GetFieldInfo
method and into the objectData.ItemsSource
property.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样的东西会有所帮助吗, 寻找 WPF 的对象图形树视图控件
否则,您可以像这样绑定到选定的树视图项,
如果您正在使用的对象中有某种属性对于 TreeView 来说,就像某种键/值对象,例如 ObjectProperty(string key, object value),它在一个名为 ObjectProperties 的集合中公开。然后您可以将其绑定到 DataGrid 并让它自动为您生成列和数据
Would something like this help, Looking for an object graph tree-view control for WPF
Otherwise you could bind to the selected tree view item like so
If you had some kind of property in the objects that you are using for the TreeView like some kind of Key/Value object, say ObjectProperty(string key, object value) and it was exposed in an collection called ObjectProperties. Then you could bind to that in your to DataGrid and have it autogenerate the columns and data fror you