In Xaml when creating a data template I can specify the type of the item the DataTemplate will be applied to like so:
<DataTemplate DataType="{x:Type Vehicle}">
<!-- do some stuff with the Vehicle class's properties -->
</DataTemplate>
I would like to be able to do the same thing when creating a DataGrid, but it's not an option with the DataType attribute:
<DataGrid ItemsSource="{Binding Cars}" DataType="{x:Type Vehicle}">
<!-- Create columns that bind to the Vehicle class's properties -->
</DataGrid>
A fairly crap workaround is to do it on each column individually:
<DataGrid ItemsSource="{Binding Cars}" DataType="{x:Type Vehicle}">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header />
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="{x:Type Vehicle}">
<!-- bind to a Vehicle class property -->
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header />
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="{x:Type Vehicle}">
<!-- bind to a Vehicle class property -->
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header />
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="{x:Type Vehicle}">
<!-- bind to a Vehicle class property -->
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Is there a better way to do this I'm unaware of? If I don't do it, various bits of ReSharper don't cope very well.
You can bind any data source that implements IEnuemerable. Each row in the DataGrid is bound to an object in the data source and each column in the DataGrid is bound to a property of the data source objects. In this example, we will create a collection of objects and bind it to a DataGrid control.
The DataGrid control provides a flexible way to display a collection of data in rows and columns. The DataGrid includes built-in column types and a template column for hosting custom content. The built-in row type includes a drop-down details section that you can use to display additional content below the cell values.
Try this:
<DataGrid ItemsSource="{Binding Cars}"
d:DesignSource="{d:DesignInstance Type={x:Type Vehicle}, CreateList=True}">
<!-- Create columns that bind to the Vehicle class's properties -->
</DataGrid>
You can specify the data context for design.
This works:
<DataGrid ItemsSource="{Binding Cars}" d:DataContext="{d:DesignInstance Type=Vehicle}">
<!-- Create columns that bind to the Vehicle class's properties -->
<!-- The pop-up window will not suggest using the Vehicle class's properties :) -->
</DataGrid>
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