Search code examples
wpfxamlresourcedictionary

ResourceDictionary shared variable


In my ResourceDictionary Resource_Color I have defined this row:

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

Now, I want to use this MainColor in another resource file, for example Resource_DataGrid.

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

. . . In this mode doesn't work. How can I write this declaration ?


Solution

  • Use 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>
    

    Also, the Foreground property is usually a Brush, not a Color. My example shows it.