2

I have a numeric column in a DataGrid I want its content be right-aligned. I have read the docs, mostly Customizable templates and styling for cells, rows and headers where I ended up with this code to accomplish right-align cell content:

<controls:DataGrid.CellStyle>
    <Style TargetType="controls:DataGridCell">
        <Style.Setters>
            <Setter Property="HorizontalAlignment" Value="Right"/>
        </Style.Setters>
    </Style>
</controls:DataGrid.CellStyle>

As is to be expected, this code really does what I want, but with all the cells. I want only the numeric column to have this property, and only it, but I have been unable to accomplish this.

What am I doing wrong?

2 Answers2

3

You have to set the HorizontalContentAlignment instead of HorizontalAlignment because the horizontal alignment changes the cell size. The default Cell HorizontalAlignment is Stretch whis is stretched the cell size to column size.

Here is a picture when you set the HorizontalAlignment cell size is changes

And Here is the picture when you set the HorizontalContentAlignment enter image description here


Basically You can define three different cell style:

    <Style x:Key="DataGridCellLeft" TargetType="controls:DataGridCell">
        <Setter Property="HorizontalContentAlignment" Value="Left" />
    </Style>
    <Style x:Key="DataGridCellCenter" TargetType="controls:DataGridCell">
        <Setter Property="HorizontalContentAlignment" Value="Center" />
    </Style>
    <Style x:Key="DataGridCellRight" TargetType="controls:DataGridCell">
        <Setter Property="HorizontalContentAlignment" Value="Right" />
    </Style>

Use it like CellStyle when you define a column.

György Gulyás
  • 1,290
  • 11
  • 37
0

I want only the numeric column to have this property, and only it

For your requirement, you could give cell style to specific DataGridTextColumn property like the follow.

<controls:DataGridTextColumn  >
    <controls:DataGridTextColumn.CellStyle>
        <Style TargetType="controls:DataGridCell">
            <Style.Setters>
                <Setter Property="HorizontalAlignment" Value="Right"/>
            </Style.Setters>
        </Style>
    </controls:DataGridTextColumn.CellStyle>
</controls:DataGridTextColumn>

The style will work for specific column.

Nico Zhu
  • 32,367
  • 2
  • 15
  • 36