Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

wpf

xaml

I define custom look for 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?

like image 743
Andrey Gordeyev Avatar asked Sep 23 '10 13:09

Andrey Gordeyev


1 Answers

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.

like image 192
ASanch Avatar answered Nov 05 '22 23:11

ASanch