I have a
DataGrid
in which I create my own columns in XAML. I am trying to centre the text in one of the column headers, using the following XAML:
<DataGridTextColumn Header="Name"
Binding="{Binding Name}"
Width="180" CanUserResize="False">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
This does centre the text, but the width of the header is set to 'auto', by which I mean it is just wide enough to contain the text 'Name' in the header. I can see this when I hover over the header: the highlight covers just the word 'Name', not the whole column header.
So I thought it would simply be a case of setting the width of the header explicitly in its style, so that it matches the width of the column, like this:
<DataGridTextColumn Header="Name"
Binding="{Binding Name}"
Width="180" CanUserResize="False">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="Width" Value="180"/>
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
This does now set the width of the header, but now my
HorizontalAlignment
is ignored and the text moves back to the left.
Why can't I do this? Does anyone know how to fix this?
What I have tried:
I also experimented with a
HorizontalAlignment
of
Stretch
, but this leaves the text left-aligned.