Create style for TextBlock in DataGridTextColumn

timmkrause picture timmkrause · Dec 3, 2013 · Viewed 26.2k times · Source

I want to create a global style that sets the VerticalAlignment to Center for all TextBlock controls inside a DataGrid or inside a DataGridTextColumn.

I don't want to copy the following into every DataGridTextColumn because it feels repetitive.

<DataGridTextColumn Header="Some Property" Binding="{Binding SomeProperty}">
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="TextBlock">
            <Setter Property="VerticalAlignment" Value="Center"></Setter>
        </Style>
    </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

I tried something like the following but it doesn't work because DataGridTextColumn does not inherit from FrameworkElement or FrameworkContentElement. DataGrid itself does but any further wrapping I try leads to errors:

<Style TargetType="DataGridTextColumn">
    <Setter Property="ElementStyle">
        <Setter.Value>
            <Style TargetType="TextBlock">
                <Setter Property="VerticalAlignment" Value="Center"/>
            </Style>
        </Setter.Value>
    </Setter>
</Style>

Answer

Michael Spranger picture Michael Spranger · Feb 10, 2016

Create a style as a static resource

<UserControl.Resources>
    <Style x:Key="verticalCenter" TargetType="{x:Type TextBlock}">
        <Setter Property="VerticalAlignment" Value="Center" />
    </Style>
</UserControl.Resources>

Then you can assign it to the ElementStyle of the DataGridTextColumn

<DataGridTextColumn ElementStyle="{StaticResource verticalCenter}" />