views:

2088

answers:

2

Hi

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

I have figured out 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, like:

<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've had a look at ResourceDictionary.MergedDictionaries, but that only lets me merge more than one external dictionary, not define further resources locally.

I must be missing something trivial?

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

A: 

Use MergedDictionaries.

I got the following example from 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>
Preet Sangha
Thanks, but no luck. His example seems right, but doesn't actually work. I get the message "The property 'Resources' is set more than once".
Tor Haugen
I know about MergedDictionaries. But they don't let me combine an external dictionary reference with locally defined resources the way I want. As already stated, there's an example on the page you refer to, but it doesn't work.
Tor Haugen
ahh sorry. Didn't realise.
Preet Sangha
+13  A: 

I figured it out. The solution involves MergedDictionaries, but the specifics must be just right, like this:

<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, the local resources must be nested within the ResourceDictionary tag. So the example here is incorrect.

Tor Haugen