6

I want to change the alignment of a header on a datagrid in Silverlight, and I can't seem to figure out how to do it. Here's what I have so far:

  <data:DataGridTextColumn Header="#" 
                            IsReadOnly="True"
                            ElementStyle="{StaticResource CenterAlignStyle}" 
                            Binding="{Binding OutlineNumber, Mode=OneWay}" >
    <data:DataGridTextColumn.HeaderStyle>
      <Style TargetType="prim:DataGridColumnHeader">
        <Setter Property="HorizontalAlignment" Value="Center"/>
      </Style>
    </data:DataGridTextColumn.HeaderStyle>
  </data:DataGridTextColumn>

No matter what I try, I can't seem to change the default alignment, which appears to be "left."

Brandon Montgomery
  • 6,924
  • 3
  • 48
  • 71

3 Answers3

9

You were really close, its:-

<Setter Property="HorizontalContentAlignment" Value="Center"/>
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
  • Actually, this does work! I didn't realize it because I wasn't resizing the column to see that the text does stay aligned to the right on the header. Thanks so much! – Brandon Montgomery Apr 16 '10 at 14:42
2

Maybe add padding to make it look better...

    <Style x:Key="HeaderCenter"
           TargetType="dataPrimitives:DataGridColumnHeader">
        <Setter Property="HorizontalContentAlignment"
                Value="Center" />
        <Setter Property="HorizontalAlignment"
                Value="Stretch" />
        <Setter Property="Padding"
                Value="12,2,2,2" />
    </Style>
jon
  • 21
  • 1
0

It seems that this approach sorta works but you get the default header, right aligned. I have a static resource style for the datagridcolumnheader and I only want to change the alignment leaving all the other style elements as contained in the custom style. So far I have:

xmlns:sdk="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
xmlns:prim="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"

and

<sdk:DataGrid  x:Name="ServicesDataGrid" Width="Auto" Margin="15,5,5,5" ColumnHeaderStyle="{StaticResource DataGridColHeaderStyle}" ......

and

<sdk:DataGridTextColumn Header="Gross Amt" Binding="{Binding GrossAmount,StringFormat=n2}" ElementStyle="{StaticResource RightAlignStyle}"> <sdk:DataGridTextColumn.HeaderStyle> <Style TargetType="prim:DataGridColumnHeader"> <Setter Property="HorizontalContentAlignment" Value="Right"/> </Style> </sdk:DataGridTextColumn.HeaderStyle> </sdk:DataGridTextColumn>

Resizing the grid shows the text is right aligned but the font, background, etc are not as defined in DataGridColHeaderStyle

Thanks

tobewan
  • 189
  • 2
  • 9