ResourceDictionary 共享变量

ResourceDictionary shared variable

在我的 ResourceDictionary Resource_Color 中我定义了这一行:

    <Color x:Key="MainColor">Black</Color>

现在,我想在另一个资源文件中使用这个MainColor,例如Resource_DataGrid

        <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Foreground" Value="{StaticResource MainColor}" />

。 . . 在这种模式下不起作用。 我该如何写这个声明?

使用ResourceDictionary.MergedDictionaries

Window1.xaml

<Window x:Class="Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="Auto" Width="Auto">
  <Window.Resources>
    <ResourceDictionary Source="Dictionary2.xaml" />
  </Window.Resources>
  <Grid>
    <TextBox Text="TESTING" FontWeight="Bold" Margin="30" />
  </Grid>
</Window>

Dictionary1.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Color x:Key="MainColor">Blue</Color>
  <SolidColorBrush x:Key="MainBrush" Color="{StaticResource MainColor}" />
</ResourceDictionary>

Dictionary2.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="Dictionary1.xaml" />
  </ResourceDictionary.MergedDictionaries>

  <Style TargetType="TextBox">
    <Setter Property="Foreground" Value="{StaticResource MainBrush}" />
  </Style>
</ResourceDictionary>

此外,前景 属性 通常是画笔,而不是颜色。我的例子展示了它。