I'm populating datagrid with collection of anonymous types (I'm setting DataGrid's DataContext
property). And there are no errors. And nothing dsiplayed in datagrid. I've tried to make the same with defined object collection, but again nothing is displayed. Please could you instruct me what to do.
Thanks!
Ok. I tried to set ItemsSource property and it works. But I'm getting strange result..
I don't know how but after 3d launch it now's working properly?
private void ShowABCResultsButtonOnClick(Object sender, RoutedEventArgs e)
{
var anonArray = new List<NormalizedResult>
{
new NormalizedResult
{
Key = 1,
Title = "Колос",
Volume = 1322.01m,
Weighted = 6.7840m,
Result = 6.7840m,
Group = "A"
},
new NormalizedResult
{
Key = 2,
Title = "Украинский Новый",
Volume = 1250.47m,
Weighted = 6.4169m,
Result = 13.2009m,
Group = "A"
},
new NormalizedResult
{
Key = 3,
Title = "Ржано-Пшеничный",
Volume = 1202.1m,
Weighted = 6.1687m,
Result = 19.3695m,
Group = "A"
}
};
this.dataGrid2.ItemsSource = anonArray;
}
this is my code.
And again I've launched.. and it displayed properly only the third time?
You likely need to do two things. The first, as @Tim suggested, is assign the query to the DataGrid.ItemsSource
property.
myDataGrid.ItemsSource = from a in x
select new { Prop1 = a.A, Prop2 = a.B, ... };
The second bit will be to enable automatic column generation on your DataGrid
:
<DataGrid x:Name="myDataGrid"
AutoGenerateColumns="True" />
Edit: I've recreated your picture using automatic column generation and anonymous types with a vanilla LINQ query. So you will need to be could use explicit columns to use or switch to a real type.
<DataGrid x:Name="myDataGrid"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Property 1"
Binding="{Binding Prop1}"/>
<DataGridTextColumn Header="Property 2"
Binding="{Binding Prop2}"/>
</DataGrid.Columns>
</DataGrid>
Edit 2: You CAN use AutoGenerateColumns="True"
just not with the bare IEnumerable<T>
where T
is an anonymous type. By adding ToList
the problem goes away.
myDataGrid.ItemsSource = (from m in typeof(int).GetMethods()
select new
{
Name = m.Name,
ReturnType = m.ReturnType.FullName
}).ToList();
XAML then goes back to:
<DataGrid x:Name="myDataGrid"
AutoGenerateColumns="True" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With