views:

35

answers:

1

I am having trouble extending one of my styles that I have defined in the Windows dictionary. Alone, it seems to apply the style to my controls as expected. However, if try to extend the style in one of my userControls, using the basedOn property, it simply overrides the main one and all the base styles dissapear. Here's an example:

In a resource dictionary, named dict1.xaml:

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Pink"/>
</Style>  

In the main window.xaml:

<Window.Resources>
    <ResourceDictionary Source="dict1.xaml"/>
</Window.Resources>

In a user control called userControl1.xaml:

<UserControl.Resources>
    <Style  BasedOn="{StaticResource {x:Type Button}}" 
            TargetType="{x:Type Button}">
        <Setter Property="FontWeight" Value="Bold"/>
    </Style>
</UserControl.Resources>

The style in the user control simply overrides the one in the resource dictionary and the font is Bold. If i remove the style in the user control, the style in the dictionary kicks in and the background becomes pink. I want both.

Any ideas what i'm doing wrong here?

thanks.

+1  A: 

You either need to add the dictionary to the UserControl resources, or add it to App.XAML resources.

As it is, the UserControl can't resolve that StaticResource -- it is in the scope of the UserControl, not the window, if that makes sense.

Jay
Yes that makes sense. When you say add it to app.xaml what will that achieve? Isn't adding it to the Windows.Resources the same thing? BTW, the app.xaml file doesn't get used in my setup because the window form is being opened from a winforms app, but that's another issue.
HAdes
@HAdes Adding it in App.XAML makes it available throughout the application, so you can reference its resources from anywhere.
Jay
So it appears that what I am after is not possible and the only way around it is to do as you suggest and copy the style into the user control. I don't like this because it's duplicating styles unnecessarily and means any modifications to the style needs doing in both. But i guess it works for now. cheers.
HAdes
@HAdes You can keep a single style in the resource dictionary; you'll just have to add the dictionary as a resource to any XAML file that references its resources using `StaticResource`. I think if you change that to `DynamicResource`, it will work as you expect (if the containing Window has the style, `BasedOn` will pick it up).
Jay