Align DataGrid Column Header to Center

后端 未结 6 812
栀梦
栀梦 2021-02-02 07:15

I need to align WPF DataGrid Column Header text to Center. I created a style and attached that using the HeaderStyle property as below

6条回答
  •  醉酒成梦
    2021-02-02 07:41

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

提交回复
热议问题