如何覆盖数据网格样式

How to override a datagrid style

我有一个样式 window,我想覆盖我应用程序中所有数据网格的数据网格样式

    <Window.Resources>          
    <Style x:Name="dtgStyle" TargetType="{x:Type DataGridRow}">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="Transparent" />
            </Trigger>

        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="Blue" />
        </Trigger>

            <Trigger Property="IsSelected" Value="False">
                <Setter Property="Background" Value="Transparent" />
            </Trigger>
        </Style.Triggers>

        <Setter Property="Background" Value="Transparent" />
        <Setter Property="Foreground" Value="White" />

    </Style>
</Window.Resources>

我认为这必须有效,但我必须申请

Style s = Resources["dtgStyle"] as Style;
mydtg.Style = s;

现在我不想将其应用于所有 dtg。 最好是在 xaml.

中自动应用它

谢谢

---添加 ASh----

感谢您的帮助。唯一的问题是,当数据网格失去焦点时,数据网格中的选定行会改变颜色,如下图所示(前景变为黑色)。

我尝试添加各种 属性 但没有任何效果。

此外,左边框变得更粗(没有双关语意)和更大。 知道如何解决吗? 谢谢

如果您需要 FrameworkElement 的默认样式,请在不使用 x:Key 的情况下声明它,仅使用 TargetType。

DataGridRow 和 DataGridCell 都有 IsSelected 属性。仅更改 DataGridRow 的背景还不够,还必须对 DataGridCell 进行更改

<Style TargetType="{x:Type DataGrid}">
    <Setter Property="RowStyle" >
        <Setter.Value>
            <Style TargetType="{x:Type DataGridRow}" BasedOn="{StaticResource {x:Type DataGridRow}}">
                <Setter Property="Background" Value="Transparent" />
                <Setter Property="Foreground" Value="White" />

                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="Transparent" />
                    </Trigger>

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

            </Style>
        </Setter.Value>
    </Setter>

    <Setter Property="CellStyle">
        <Setter.Value>
            <Style TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource {x:Type DataGridCell}}">
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Background" Value="Orange" />
                    </Trigger>

                    <DataTrigger Binding="{Binding IsKeyboardFocusWithin, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" Value="False">
                        <Setter Property="Foreground" Value="White"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Setter.Value>
    </Setter>
</Style>

在此处找到前景修复:DataGrid's selected row color when inactive ()