WPF Datagrid 选定行颜色和居中文本

WPF Datagrid Selected Row Color and Centered Text

我有一个简单的 DataGrid,我想在其中设置所选行的样式并将文本居中。我已经尝试了以下但它不起作用:

<DataGrid.CellStyle>
    <Style TargetType="{x:Type DataGridCell}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridCell}">
                    <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Background" Value="Blue" />
                <Setter Property="Foreground" Value="White" />
            </Trigger>
        </Style.Triggers>
    </Style>
</DataGrid.CellStyle>

为什么以上不能一起工作?如果我移除触发器,它会居中,但不会使用我想要的颜色。

尝试将 Grid 添加到 DataGridCell 样式的 ControlTemplate:

<Style TargetType="{x:Type DataGridCell}">
    <Setter Property="Background" Value="Transparent" />

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter Margin="2"
                                      VerticalAlignment="Center"
                                      HorizontalAlignment="Center" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Foreground" Value="White" />
            <Setter Property="Background" Value="Blue" />
        </Trigger>
    </Style.Triggers>
</Style>