xamldatagridwinui-3winuiwindows-community-toolkit

I have a c# WinUI 3 desktop application (VS 2019) - right align text in a datagrid cell


Using a datagrid. I would like to right align certain columns. The way I tried it below does not work. Does anyone know the correct way? Thanks a lot.

        <Grid Grid.Row="2" HorizontalAlignment="Center">
            <controls:DataGrid x:Name="Results_DataGrid"  
                           AutoGenerateColumns="False"
                           CanUserSortColumns="False"
                           AreRowDetailsFrozen="True"
                           BorderBrush="#005986"
                           BorderThickness="2 2 2 2"
                           Margin="3 10 3 5"
                           PointerReleased="Results_DataGrid_PointerReleased">
                <controls:DataGrid.Columns>
                    <controls:DataGridTextColumn
                            Header="Jan"
                            Width="SizeToHeader"
                            Binding="{Binding Jan}"
                            FontSize="11"
                            Foreground="Black" 
                            >
                        **<controls:DataGridTextColumn.ElementStyle>
                            <Style TargetType="controls:DataGridCell">
                                <Setter Property="HorizontalAlignment" Value="Right"/>
                            </Style>
                        </controls:DataGridTextColumn.ElementStyle>**
                    </controls:DataGridTextColumn>
                </controls:DataGrid.Columns>
            </controls:DataGrid>

Solution

  • The ElementStyle in the DataGridTextColumn targets a TextBlock.

    <controls:DataGridTextColumn.ElementStyle>
        <Style TargetType="TextBlock">
            <Setter Property="HorizontalTextAlignment" Value="Right" />
        </Style>
    </controls:DataGridTextColumn.ElementStyle>
    

    I also can use the CellStyle for this.

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