How to combine imported and local resources in WPF user management

I am writing several WPF user controls that need both shared and individual resources.

I understood the syntax for loading resources from a separate resource file:

<UserControl.Resources> <ResourceDictionary Source="ViewResources.xaml" /> </UserControl.Resources> 

However, when I do this, I cannot also add resources locally, for example:

 <UserControl.Resources> <ResourceDictionary Source="ViewResources.xaml" /> <!-- Doesn't work: --> <ControlTemplate x:Key="validationTemplate"> ... </ControlTemplate> <style x:key="textBoxWithError" TargetType="{x:Type TextBox}"> ... </style> ... </UserControl.Resources> 

I looked at ResourceDictionary.MergedDictionaries, but this only allows me to combine more than one external dictionary, rather than define additional resources locally.

Do I need to miss something trivial?

It should be noted: I host my user controls in a WinForms project, so hosting shared resources in App.xaml is not really an option.

+71
resources wpf xaml
Aug 26 '09 at 10:37
source share
3 answers

I get it. The solution includes MergedDictionaries, but the features should be in order, for example:

 <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ViewResources.xaml" /> </ResourceDictionary.MergedDictionaries> <!-- This works: --> <ControlTemplate x:Key="validationTemplate"> ... </ControlTemplate> <style x:key="textBoxWithError" TargetType="{x:Type TextBox}"> ... </style> ... </ResourceDictionary> </UserControl.Resources> 

That is, local resources must be nested inside the ResourceDictionary tag. So the example here is incorrect.

+140
Aug 26 '09 at 10:55
source share

Use MergedDictionaries .

I got the following example here.

File1

 <ResourceDictionary xmlns=" http://schemas.microsoft.com/winfx/2006/xaml/presentation " xmlns:x=" http://schemas.microsoft.com/winfx/2006/xaml " > <Style TargetType="{x:Type TextBlock}" x:Key="TextStyle"> <Setter Property="FontFamily" Value="Lucida Sans" /> <Setter Property="FontSize" Value="22" /> <Setter Property="Foreground" Value="#58290A" /> </Style> </ResourceDictionary> 

File 2

  <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="TextStyle.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> 
+4
Aug 26 '09 at 10:40
source share

You can define local resources in the MergedDictionaries section:

 <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <!-- import resources from external files --> <ResourceDictionary Source="ViewResources.xaml" /> <ResourceDictionary> <!-- put local resources here --> <Style x:key="textBoxWithError" TargetType="{x:Type TextBox}"> ... </Style> ... </ResourceDictionary> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </UserControl.Resources> 
+3
Oct 10 2018-11-11T00:
source share



All Articles