如何更改 DataGrid 应用程序的 SystemColors

How to change the SystemColors of a DataGrid app wide

我知道如何像这样更改特定 UIElement 的 SystemColor

<DataGrid>
  <DataGrid.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightGray" />
  </DataGrid.Resources>
</DataGrid>

但我想为我的应用程序中的所有 DataGrid 进行此设置。如何在我的 app.xaml 文件中进行设置以使其正常工作?这显然行不通:

<Style TargetType="{x:Type DataGrid}">
  <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightGray" />
</Style>

放在Style的资源中:

<Style TargetType="DataGrid">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightGray" />
    </Style.Resources>
</Style>

在此之前,您需要执行几个步骤。

1。创建资源字典

Microsoft documentation 之后,您需要创建一个资源字典并用您想要的元素填充它。像这样:

<ResourceDictionary x:Key="whatever">
    <Style TargetType="DataGrid">
        <Setter Property="Background" Value="Aqua" />
    </Style>
</ResourceDictionary>

将其保存在单独的 XAML 文件中,可能 DataGridStyles.xaml

2。在您的应用程序中包含 ResourceDictionary

现在我们需要在我们的应用程序中包含 ResourceDictionary。我将使用 merged resource dictionaries 执行此操作。这可以在多个不同的级别上完成。如果您希望它是全球性的,请在 App.xaml

中执行此操作
<Application.Resources>
     <ResourceDictionary>
         <ResourceDictionary.MergedDictionaries>
             <ResourceDictionary Source="DataGridStyles.xaml" />
             <!-- Include any amount of Resource Dictionaries you want -->
         </ResourceDictionary.MergedDictionaries>
     </ResourceDictionary>
</Application.Resources>

您可能需要 fiddle 使用 <ResourceDictionary ... /> 标签的 Source 属性 来使其引用正确的 XAML 文件并让它在发布时也包含它。我个人建议使用 pack URIs

当您正确执行此操作时,样式应该正确导入到从 App.xaml 运行的所有内容中。这种方法还提供了其他好处,例如能够组织您的样式并将它们集中起来而不是通过应用程序分散开来。此外,这种方法还可以让您在运行时以最少的代码更改来切换样式。