Generic styles for DataGridTemplateColumn Headers & Cells

Posted by user557765 on Stack Overflow See other posts from Stack Overflow or by user557765
Published on 2010-12-30T01:50:35Z Indexed on 2010/12/30 1:53 UTC
Read the original article Hit count: 611

Filed under:
|

I am struggling to define templates for my DataGrid columns. Here is the code that I have working at the moment:

        <t:DataGrid.Columns>
            <t:DataGridTemplateColumn Width="75" >
                <t:DataGridTemplateColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock Style="{StaticResource FieldNameVertical}" Text="Date" />
                    </DataTemplate>
                </t:DataGridTemplateColumn.HeaderTemplate>
                <t:DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Style="{StaticResource FieldValue}" Text="{Binding ModifiedDate, StringFormat='{}{0:MM/dd/yyyy}'}" />
                    </DataTemplate>
                </t:DataGridTemplateColumn.CellTemplate>
            </t:DataGridTemplateColumn>
            ..
            ..
            ..
        </t:DataGrid.Columns>

I would like to define HeaderTemplate & CellTemplate as reusable styles -- so that each column would be as brief as something like this:

        <t:DataGrid.Resources>
            <DataTemplate x:Key="dgHeaderStyle">
                <TextBlock Style="{StaticResource FieldNameVertical}" Text="{Binding}" />
            </DataTemplate>
            <DataTemplate x:Key="dgCellStyle">
                <TextBlock Style="{StaticResource FieldValue}" Text="{Binding}" />
            </DataTemplate>
        </t:DataGrid.Resources>
        <t:DataGrid.Columns>
            <t:DataGridTemplateColumn Width="75" Header="Date"
                Binding="{Binding ModifiedDate, StringFormat='{}{0:MM/dd/yyyy}'}"
                HeaderTemplate="{StaticResource dgHeaderStyle}" CellTemplate="{StaticResource dgCellStyle}" />
            <t:DataGridTemplateColumn Width="100" Header="Dealer"
                HeaderTemplate="{StaticResource dgHeaderStyle}" CellTemplate="{StaticResource dgCellStyle}" />
            ...
        </t:DataGrid.Columns>

Every attempt I make has failed. I had hoped to implement something like the "solution" snippet in the initial entry of WPF DataGrid HeaderTemplate Mysterious Padding. However, I can't seem to adapt it to what I'm doing.

© Stack Overflow or respective owner

Related posts about wpf-binding

Related posts about wpfdatagrid