次の方法で共有


WPF Resources

I've been playing around and learning about WPF (Avalon) resources and ResourceDictionaries recently.  I had a few questions pop up that the knowledgeable people on the Avalon team graciously answered for me.  (Thanks to Rob Relyea, WeiBing Zhan, and Ashish Shetty)

Here's a recap:

1) I used to look at resources in reflector or ildasm, how can I see inside WPF resources?

As it turns out, reflector is still the tool du jour!

Figure 1: Reflector's view of WPF Resources

2) What's the difference between:

<ResourceDictionary Source="ResourceDictionary.xaml"/>

and

<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="ResourceDictionary.xaml"/>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

The answer to this may seem obvious however the examples I had seen up to that point and the fact that I only had Chris Sells book to go on (which doesn't cover MergedDictionaries) left me wondering. 

In both cases you end up with the same resources, the reason for the ResourceDictionary.MergedDictionaries property is to allow for this:

<ResourceDictionary>
    <SolidColorBrush x:Key="myRed" Color="Red" Opacity="0.5"/>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="ResourceDictionary.xaml"/>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

Since the following is not valid:

<Window.Resources>
    <ResourceDictionary Source="ResourceDictionary.xaml"/>
    <SolidColorBrush … />  <!—this solid color brush is not allowed
</Window.Resources>

3) What is the difference between setting the build action on a XAML file that only contains a ResourceDictionary to page and to resource?

In other words, suppose you have a XAML file that contains only a ResourceDictionary – should you use the “Page”, “Resource” or “Embedded Resource” build action?

You don’t want to use “Embedded Resource” – that simply doesn’t work. Specifying “Embedded Resource” puts the resource in the .mresource section of the assembly, these resources need to go in the g.resources section (which in turn is in the .mresource section).

Most likely you’ll want to use the “Page” setting as it creates a .baml file, which adds compile time checking and improved runtime performance.

You can use Reflector to inspect the generated resources:

Figure 2: Build action "Page" generates a more performant BAML file.

Figure 3: Build action "Resource" generates an embedded XAML file.

Comments

  • Anonymous
    April 05, 2006
    Jim has posted the results of his recent inquiry on this subject&amp;nbsp;as well as some other goodness...
  • Anonymous
    September 19, 2006
    WPF Resources
    A while back, Jim posted a summary of the different types of resources in WPF.&amp;nbsp; We...