WPF - 在字典中定义的样式与父控件中定义的样式混合

6

我在一个资源字典中定义了一个Button控件的自定义外观:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Style TargetType="Button" x:Key="BaseButtonStyle">
    <Setter Property="Background" Value="Blue"/>
  </Style>
</ResourceDictionary>

然后我尝试更改包含按钮的窗口的样式。

<Window.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="Dictionary.xaml"/>
      <ResourceDictionary>
        <Style TargetType="Button" BasedOn="{StaticResource BaseButtonStyle}">
          <Setter Property="Foreground" Value="Red"/>
        </Style>
      </ResourceDictionary>
      </ResourceDictionary.MergedDictionaries>   
    </ResourceDictionary>
</Window.Resources>

在WPF设计师中,我得到了我期望的效果:一个蓝色按钮和红色文本。 但是在运行时,两种样式都没有应用,按钮显示默认颜色。 我该如何解决这个问题?

1个回答

7
下面的代码有效。我只是将Style从MergedDictionaries中移出,并将其放在外部ResourceDictionary中。
<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Dictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>

        <Style TargetType="Button" BasedOn="{StaticResource BaseButtonStyle}">
            <Setter Property="Foreground" Value="Red"/>
        </Style>
    </ResourceDictionary>
</Window.Resources>

在您的原始XAML中,我不确定为什么设计师能够正确呈现它,而WPF运行时没有。然而MSDN文档指出:

合并的ResourceDictionary在标记中没有定义资源元素。相反,合并的字典是一个ResourceDictionary,其中没有定义标记子元素(或通过代码添加的元素),但指定了URI。

这可能与此有关。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接