Text alignment in a WPF DataGrid

后端 未结 13 734
野性不改
野性不改 2020-12-14 14:13

How can I align the column data to center in a WPF DataGrid?

相关标签:
13条回答
  • Or in code behind:

    grid.CellStyle = newCellStyle();
    
    public static Style newCellStyle()
    {
        //And here is the C# code to achieve the above
        System.Windows.Style style = new Style(typeof(DataGridCell));
        style.Setters.Add(new System.Windows.Setter
        {
            Property = Control.HorizontalAlignmentProperty,
            Value = HorizontalAlignment.Center
        });
        return style;
    }
    
    0 讨论(0)
  • 2020-12-14 14:33

    Ok, I used the frameworkElement approach but there was a strange behavior when you try to highlight the row.

    I've put another example of WPF Datagrid alignment in this thread!

    0 讨论(0)
  • 2020-12-14 14:34

    I ended up having problems with the cell being shifted and looking funky using the accepted answer. I know it's late, but hopefully my findings will help someone. I use:

    <DataGridTextColumn.ElementStyle>
         <Style>
              <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
         </Style>
    

    rather than the CellStyle.

    0 讨论(0)
  • 2020-12-14 14:39

    If you are using DataGridTextColumn you can use the following code snippet:

    <Style TargetType="DataGridCell">
         <Style.Setters>
                <Setter Property="TextBlock.TextAlignment" Value="Center" />
         </Style.Setters>
    </Style>
    
    0 讨论(0)
  • 2020-12-14 14:39

    I really like Bruno's TextBlock.TextAlignment approach. You can use this in conjunction with horizontal alignment and then any background will stretch across the whole grid cell.

    e.g. (in VB)

        Dim sty = New System.Windows.Style(GetType(DataGridCell))
        sty.Setters.Add(New Setter(HorizontalAlignmentProperty, HorizontalAlignment.Stretch))
        sty.Setters.Add(New Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right))
        sty.Setters.Add(New Setter(BackgroundProperty, Brushes.LightGray))
    
    0 讨论(0)
  • 2020-12-14 14:43

    For me this one works well

    <DataGridTextColumn Width="1*" Binding="{Binding Balance, StringFormat=C} "Header="Balance">
      <DataGridTextColumn.CellStyle>
          <Style>
            <Setter Property="TextBlock.TextAlignment"  Value="Right"/>
          </Style>
       </DataGridTextColumn.CellStyle>
     </DataGridTextColumn>
    
    0 讨论(0)
提交回复
热议问题