I have a query that returns 2 columns from joining 2 entities as the following:
var myQ = myDataContext1.Entity1.Join(myDataContext1.Entity2, a=>a.id, b=>b.id, (a, b)=> new Tuple<int, float>(a.id, b.something)).ToList();
MyDatagrid.ItemSources = myQ;
It worked fine. But my datagrid labels the 2 columns as 'item1' and 'item2'. I tried to change them to the right names. So far I could not do it. I tried to use:
MyDatagrid.Columns.Add(new DataGridTextColumns{ Header = "Aheader", Binding= new System.Windows.Data.Binding("a.id");
All the data would disappear because the binding name must be wrong. But I have no idea what I should put following Binding... Then, I tried
MyDataGrid.Columns[0].Header = "myID"
It does not work and tells me every time that there were no columns in the column collection. So I think the change of the header must happen after the datagrid is loaded and added an event:
MyDataGrid.loaded += (o, e) =>{MyDataGrid.Columns[0].Header = "myID"};
Still the same error..... Any idea what I should do here? Thanks.
The binding needs to be Item1 and Item2. You should also set AutoGenerateColumns to false and it is preferrable to define the columns in XAML. eg
<DataGrid AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Item1}" Header="Header 1"></DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Path=Item2}" Header="Header 2"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
You might also be better off using an anonymous type instead of a tuple. That way the binding could be more meaningful.