2

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.

3
  • You should not have to use reflection for a master/details approach Dec 15, 2010 at 15:01
  • I need to list all the fields of the object in the Tag (the objects can be arbitary types) and the field values in the grid. How am I meant to do that without using reflection?
    – thecoop
    Dec 15, 2010 at 15:04
  • Couple of things...skip the Tag property as it couples the View significantly and tie your data back into your VieWModel via the TreeView.SelectedItem property; where once a user selects a new node your DataGrid will get updated via the ViewModel instead of trying to extract data out of the Tag. Whatever data you want out of the model I would put something on the model itself to return the values; perhaps abstract it away in a base class/interface (yes you will still need reflection as you stated for that effort) Dec 15, 2010 at 15:16

1 Answer 1

0

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

<DataGrid Name="objectData" DataSource={Binding ElementName=objectList, Path=SelectedItem} />

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

<DataGrid Name="objectData" DataSource={Binding ElementName=objectList, Path=SelectedItem.ObjectProperties} />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.