The following contrived example illustrates my problem.
My ViewModel:
public class MyViewModel : ViewModel
{
public MyViewModel()
{
var table = new DataTable("MyDatatable");
table.Columns.Add("Some Val", typeof(double));
table.Columns.Add("Ref");
var row = table.NewRow();
row["Some Val"] = 3.14;
row["Ref"] = new {Title = "My Title", Description = "My Description"};
table.Rows.Add(row);
MyDataView = table.DefaultView;
}
DataView MyDataView { get; set; }
}
Now my problem lies in my Xaml code. I want one of my column headers to be “My Title” with the corresponding row value to be “My Description”…
My Xaml:
<DataGrid ItemsSource="MyDataView" AutoGenerateColumns="False">
<DataGrid.Columns>
<!--This column works fine. -->
<DataGridTextColumn Header="Some Val" Binding="{Binding 'Some Val'}" Width="50"/>
<!--This column doesn't work... I'm looking for something similar to this: -->
<DataGridTextColumn Header="{Binding Path='Ref.Title'}" Binding="{Binding Path='Ref.Description'}"/>
</DataGrid.Columns>
</DataGrid>
Does this make sense? The second column header should be “My Title” with the cell value being “My Description”. Any idea on how to do this?
I believe your second column should be:
EDIT:
Ok, it looks like the DataGridTextColumn will not inherit the DataContext from the DataGrid. In fact, it’s not a FrameworkElement or Freezable so it won’t have a DataContext at all.
The column should apply to any number of rows, even if you only have 1 row. The Header needs to be generic for all rows, while the Binding is row specific. But, you are trying to bind both to the first row.
If you actually had two rows with different titles, then which should be displayed in the header?
For Description, the following works:
With the XAML looking like:
If you remove the
typeof(Test)part when defining the column, thenPath=[Ref]will refer to a string, not an object of type Test. So I don’t think you’ll be able to use anonymous types.JP Richardson’s EDIT:
Based upon CodeNaked’s answer, I was reminded of some previous problems that I knew solutions to, these allowed me to completely solve the problem.
First, it is possible to bind to anonymous datatypes. The code modification should be be:
Instead of:
As CodeNaked stated, without the typeof(object) the default object type is assumed to be a string.
Also, as CodeNaked stated, the DataGridTextColumn does not ‘know’ either DataContext for the row or the DataGrid. For every Window object (typicall MVVM scenario, there is just one) should have this code in place:
And then call “RegisterDataGridColumnsToDataContext()” before the Window is shown.
Modify MyViewModel to look like this:
The modified Xaml would then look like this:
Note: Originally the reason that I had the column header title in each row was that I couldn’t think of another way to bind it to the ‘Header’ property of my DataGridTextColumn. I was planning for the ‘Title’ property of each anonymous object to be the same. Fortunately the internet prevails.