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

时间:2015-01-23 06:43:18

标签: wpf xaml datagrid styles

我有一个简单的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>

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

1 个答案:

答案 0 :(得分:0)

尝试将 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>