Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF not applying default styles defined in MergedDictionaries?

Tags:

c#

wpf

.net-4.0

In a WPF application I defined default control styles in separate resource dictionaries (e.g. "ButtonStyle.xaml"), and added them as merged dictionaries to a resource dictionary named "ResDictionary.xaml".

If I refer this "ResDictionary.xaml" as merged dictionary in my App.xaml, the default styles are not applied. However, if I refer the "ButtonStyle.xaml", it works correctly.

If I recompile the same code in .NET 3.5 or 3.0, it recognizes and applies the default styles referred in "App.xaml" through "ResDictionary.xaml", but not in .NET 4.0.

At runtime if I check the Application.Current.Resources dictionary, the default styles are there, but they are not applied, only if I specify the Style property explicitly in the Button control.

Are there any solutions to refer a resource dictionary (containig default styles) this way in .NET 4.0?


App.xaml:

<Application.Resources>   <ResourceDictionary>     <ResourceDictionary.MergedDictionaries>       <ResourceDictionary Source="Styles/ResDictionary.xaml"/>     </ResourceDictionary.MergedDictionaries>   </ResourceDictionary> </Application.Resources> 

ResDictionary.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">     <ResourceDictionary.MergedDictionaries>         <ResourceDictionary Source="Default/ButtonStyle.xaml"/>     </ResourceDictionary.MergedDictionaries> </ResourceDictionary> 

ButtonStyle.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">     <Style TargetType="Button">         <Setter Property="Background" Value="Yellow"/>     </Style> </ResourceDictionary> 
like image 506
Burgberger Avatar asked May 02 '10 13:05

Burgberger


1 Answers

The best solution is to add a dummy default style in the resource dictionary where you merge all resources together.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">  <ResourceDictionary.MergedDictionaries>     <ResourceDictionary Source="Style/Button.xaml"/> </ResourceDictionary.MergedDictionaries>  <Style TargetType="Control" BasedOn="{StaticResource {x:Type Control}}" /> 

like image 158
Christian Moser Avatar answered Sep 29 '22 09:09

Christian Moser