开发者

WPF - Mixing style defined in dictionary with style defined in parent control

开发者 https://www.devze.com 2023-01-17 20:06 出处:网络
I define custom look f开发者_如何学Cor Button control in resource dictionary: <ResourceDictionary xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"

I define custom look f开发者_如何学Cor Button control in resource dictionary:

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

Then I try to change the style in window were the buttons are located.

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

In WPF designer I have what I expected. Blue button with the red text. But in run-time both styles are not applied and the button has default colors. How can I fix this?


The one below works. I just moved the Style out of the MergedDictionaries and placed it on the outer 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>

In your original XAML, I'm not sure why the designer was able to render it correctly while the WPF runtime didn't. The MSDN documentation says though that:

A merged ResourceDictionary does not have resource elements defined within it in markup. Instead, the merged dictionary is a ResourceDictionary with no markup child elements defined (or with no elements added through code), but with a URI specified for Source.

It might have something to do with it.

0

精彩评论

暂无评论...
验证码 换一张
取 消