Click here to Skip to main content
15,887,822 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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.
Posted
Updated 21-Oct-19 12:00pm

1 solution

Set the "header" directly (it's a "content" control):

<DataGridTextColumn>
   <DataGridTextColumn.Header>
      <TextBlock Text="Name"
                 HorizontalAlignment="Stretch"
                 TextAlignment="Center" />
   </DataGridTextColumn.Header>
</DataGridTextColumn>
 
Share this answer
 
Comments
Patrick Skelton 22-Oct-19 4:54am    
Thank you for the answer. That is an interesting point I had overlooked but it doesn't seem to fix the problem for me. The text is always left-aligned when I apply Stretch to the TextBlock.

Maybe I should post my entire XAML for this part of the window. Maybe something I'm doing higher up the visual tree is breaking things.
laurrylf 7-Apr-20 18:07pm    
<datagridtextcolumn.headerstyle>

<Setter Property="HorizontalContentAlignment" Value="Stretch"/>

Patrick Skelton 8-Apr-20 2:44am    
Thanks for the reply. I'll give it a try when I get back onto that part of the project.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900