是否可以引用资源字典并在同一资源部分中定义样式?

时间:2011-07-14 12:39:28

标签: wpf xaml styles resourcedictionary

像这样:

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

如果我这样做,我会收到有关background1和background2未解析的警告以及XamlParseException,因为窗口的Resource属性已经定义(它不是)。如果我删除这些东西,一切都很好。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

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>