XAML WPF -混合字典中定义的样式和父控件中定义的样式

tpgth1q7  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(124)

我在资源字典中定义了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设计器中得到了我所期望的:一个带有红色文本的蓝色按钮。但是在运行时,这两种样式都没有应用,按钮有默认颜色。我该如何解决这个问题?

qncylg1j

qncylg1j1#

下面这个可以用。我只是把样式从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运行时却不能。

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

可能和这件事有关。

相关问题