DataGridCell DataTemplate access to data item

Oct 14, 2008 at 3:07 PM
Edited Oct 14, 2008 at 3:09 PM
I'll give a simplified description of what I'd like to do:
I have a DataGrid with a System.Data.DataTable as ItemsSource and I do not want to declare the DataGridColumns explicitly since I'm dynamically adding columns to the DataTable. Each row in the DataTable contains a number of complex objects (of the same type) for which I'd like to show one property. I thought that the following XAML would do the trick:

<Style TargetType="dg:DataGridCell">
    <Setter Property
                <TextBlock Text="{Binding Path=SomeProperty}" />

<dg:DataGrid ItemsSource="{Binding Path=MyItems}" IsSynchronizedWithCurrentItem="True" />

This fails since the Content of the DataGridCell seems to be a System.Data.DataRowView rather than the data item itself. The only way I've found to get to the data item through the DataRowView is by using the indexer property with the column name or index (which are not readliy available, I think). How do I do this?
Nov 2, 2008 at 4:16 PM
Binding to ItemsSource properties do not work well in this way.  What you can do set the binding on the column as you are adding them dynamically.  Have you tried that already?
Nov 3, 2008 at 8:40 AM
No, I haven't tried that.

What I did was to use an ugly workaround where I first generate the DataGridColumns in code behind, as needed, and expose the DataTable column names associated with the DataGridColumns in an IDictionary<DataGridColumn, string> as a dp on my page. Then I use a multibinding to bind to this dp, to the DataGridCell DataContext (i.e. the DataRowView) and to the DataGridColumn of the cell and lookup the data item in a converter. Nothing I'm proud of but it did the trick.

However, any improvement is welcome, but I don't really understand what you mean with setting the binding on the column (the DataColumn or the DataGridColumn?). An example demonstrating what you mean would be greatly appreciated.

Thank you,
Nov 3, 2008 at 1:17 PM
The sample on this post,, has an example of using a DataTable as the data source.  The columns are not dynamic but it should still give you an idea on how to declare the binding on the column.  It is not that difficult to take the sample and make the column generation dynamic.  Hope that helps.