Align DataGrid Column Header to Center

There is a response for doing it programmatically at AutoGeneratingColumn:

 private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
                e.Column.HeaderStyle = new Style(typeof(DataGridColumnHeader));
                e.Column.HeaderStyle.Setters.Add(new Setter(HorizontalContentAlignmentProperty, HorizontalAlignment.Center));

    }

Tip, use attributes:

public class ColumnNameAttribute : Attribute
{
    public HorizontalAlignment Alignment { get; set;}
    public ColumnNameAttribute(HorizontalAlignment alignment){
        Alignment = alignment;
}

public class Example(){
    [ColumnName(HorizontalAlignment.Center)]
    public string Column {get; set;}
}

 private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
   var desc = e.PropertyDescriptor as PropertyDescriptor;
   var att = desc.Attributes[typeof(ColumnNameAttribute)] as ColumnNameAttribute;
   if(att != null){
           e.Column.HeaderStyle = new Style(typeof(DataGridColumnHeader));
           e.Column.HeaderStyle.Setters.Add(new Setter(HorizontalContentAlignmentProperty, att.Alignment));
    }

}

It should be StaticResource instead of DynamicResource in the Column:

Style

<Window.Resources>
    <Style x:Key="CenterGridHeaderStyle" TargetType="DataGridColumnHeader">
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
    </Style>
</Window.Resources>

Column

<DataGridTextColumn 
   Binding="{Binding Path=Name}" Header="Name" IsReadOnly="True" 
   HeaderStyle="{StaticResource CenterGridHeaderStyle}"/>

Check this

<DataGridTextColumn Header="Nombre"
                          Binding="{Binding Nombre}">
<DataGridTextColumn.HeaderStyle>
  <Style TargetType="DataGridColumnHeader">
     <Setter Property="HorizontalContentAlignment"
                 Value="Center" />
  </Style>
</DataGridTextColumn.HeaderStyle>

Tags:

C#

Wpf

Datagrid