10
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 unawar