Search code examples
wpfxamlstylesresourcedictionary

Is it possible to reference a resource dictionary and define a style in the same resource section?


Like so:

<Window x:Class="WpfApplication3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525">

    <Window.Resources>
        <ResourceDictionary x:Key=""whatever" Source="colors.xaml" />
        <Style TargetType="Button">
            <!- button style using colors defined in colors.xaml -->
        </Style>
    </Window.Resources>

    <StackPanel>
        <Button Background="{DynamicResource background1}" Height="50"></Button>
        <Button Background="{DynamicResource background2}" Height="50"></Button>
    </StackPanel>

</Window>

If I do that I get warnings about background1 and background2 not being resolved and an XamlParseException, because the Resource property of window is already defined (it is not). Everything is fine if I remove the stuff.

Any ideas?


Solution

  • It's easy with MergedDictionaries

    <Window.Resources>
       <ResourceDictionary>
         <ResourceDictionary.MergedDictionaries>
           <ResourceDictionary x:Key=""whatever" Source="colors.xaml" /> 
        </ResourceDictionary.MergedDictionaries>
        <Style TargetType="Button">
             <!- button style using colors defined in colors.xaml -->
        </Style>
      </ResourceDictionary>
    </Window.Resources>