Align DataGrid Column Header To Center


Answer :

Check this

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

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}"/> 

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));     }  } 

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable