Defining and Using Shared Resources in a Custom Control Library



The question about how to define and use shared resources in a custom library has come up a couple times lately and after much discussion with the developer (thanks Varsha), here is the answer.


 


When an application looks for a resource, it looks at three levels in the following order:


 



  1. The element level—This is the level at which the system starts with the element that references the resource then searches resources of the logical parent and so forth until the root element is reached.

  2. The application level—Resources are defined by the Application object.

  3. The theme level– The theme level dictionaries are stored in a subfolder called Themes.  The files in the Themes folder correspond to a theme.  For example, you might have Aero.NormalColor.xaml, Luna.NormalColor.xaml, Royale.NormalColor.xaml, etc.  You can also have a file called generic.xaml.  When the system looks for a resource at the themes level, it first looks for it in the theme-specific file and then looks for it in generic.xaml.

For more information about resources, see Resources in the WPF SDK.


 


As a control library developer, you don’t have access to the Application object, so you have to put your resources at the element level or at the theme level. 


 


Defining resources at the element level


 


You can define shared resources at the element level by creating a custom resource dictionary and merging it with your control’s resource dictionary.  When you use this method, you can call your resource file anything you want and it can be in the same folder as your controls. Resources at the element level can also use simple strings as keys. The following shared resource is defined in a file called Dictionary1.XAML (nothing new here).


 


  <LinearGradientBrush


    x:Key=myBrush 


    StartPoint=0,0 EndPoint=1,1>


    <GradientStop Color=Red Offset=0.25 />


    <GradientStop Color=Blue Offset=0.75 />


  </LinearGradientBrush>


 


Once you’ve defined your dictionary, you need to merge it with your control’s ResourceDictionary.  You can do this using XAML or code.


 


Merging the ResourceDictionary in XAML


To merge the resource dictionary using XAML, include the following in the XAML file of your custom control (in this case, a UserControl):


 


  <UserControl.Resources>


    <ResourceDictionary>


      <ResourceDictionary.MergedDictionaries>


        <ResourceDictionary Source=Dictionary1.xaml/>


      </ResourceDictionary.MergedDictionaries>


    </ResourceDictionary>


  </UserControl.Resources>


 


When you reference a ResourceDictionary in XAML, a ResourceDictionary object is created each time you reference it.  So if you have 10 custom controls in your library and merge the shared ResourceDictionaries for each control by using XAML, you create 10 identical ResourceDictionary objects.  You can avoid this by creating a static class that returns the ResourceDictionary and merging the resources in code. 


 


Merging the ResourceDictionary in Code


Here is a class that returns a shared ResourceDictionary.


 


    internal static class SharedDictionaryManager


    {


        internal static ResourceDictionary SharedDictionary


        {


            get


            {


                if (_sharedDictionary == null)


                {


                    System.Uri resourceLocater =


                        new System.Uri(“/CustomControlLibrary2;component/Dictionary1.xaml”,


                                        System.UriKind.Relative);


 


                    _sharedDictionary =


                        (ResourceDictionary)Application.LoadComponent(resourceLocater);


                }


 


                return _sharedDictionary;


            }


        }


 


        private static ResourceDictionary _sharedDictionary;


    }


 


Then in the constructor of each custom control, merge the shared resource with the resources of the custom control before you call InitilizeComponent.  Because the property is static, the ResourceDictionary gets created only once.


 


this.Resources.MergedDictionaries.Add(SharedDictionaryManager.SharedDictionary);


 


Defining resources at the theme level


 


When you define a resource at the theme level, you must create a ComponentResourceKey for the resource of the key.  This isn’t too difficult, but it’s not as simple as assigning a string as the key.


 


  <LinearGradientBrush


        x:Key={ComponentResourceKey TypeInTargetAssembly={x:Type local:Painter},


                                 ResourceId=ButtonBrush} 


        StartPoint=0,0 EndPoint=1,1>


    <GradientStop Color=Blue Offset=0 />


    <GradientStop Color=White Offset=.8 />


  </LinearGradientBrush>


 


The TypeInTargetAssembly property indicates a type that is in the same assembly as generic.xaml.  It doesn’t restrict the types within the library that can use the resource.  To use the resource in a control, simply reference it by a ComponentResourceKey:


 


    <Button  Margin=0,10,0,0 Click=FillBrush


             Background={StaticResource {ComponentResourceKey


                            TypeInTargetAssembly={x:Type local:Painter},


                            ResourceId=ButtonBrush}}>


      Paint ellipse


    </Button>


 


Note:  Visual Studio automatically created Themes/generic.xaml when you create a new custom control but not when you create a user control.  To use Themes/generic.xaml in a library of user controls, manually create the folder, create a new resource dictionary in that folder, and name it generic.xaml.


 


Accessing the shared resources


 


Regardless of what method you choose to create a shared dictionary, you can use the shared resources in XAML or code, just as you would any other resource.  Remember that the difference in the two is the type of the x:Key: Resources defined at the them level must be referenced by a ComponentResourceKey, while resources at the element level can be referenced by a string.


 


    <!–myBrush is a shared resource in dictionary1.xaml.–>


    <Rectangle Width=200 Height=200


               Stroke=Black StrokeThickness=2


               Fill={StaticResource myBrush}/>


 


    <!–ButtonBrush is a resource in generic.xaml->


    <Button  Margin=0,10,0,0 Click=FillBrush


             Background={StaticResource {ComponentResourceKey


                            TypeInTargetAssembly={x:Type local:Painter},


                            ResourceId=ButtonBrush}}>


      Paint ellipse


    </Button>


 


To get and use resources in code, use the FindResources or TryFindResources method.  These methods are defined for FrameworkElement and FrameworkContentElement, so you can call them directly on your control.


 


            // MyEllipseBrush is a theme level resource so it has a ComponentResourceKey.


            ComponentResourceKey brushKey = new ComponentResourceKey(typeof(Painter), “MyEllipseBrush”);


            ellipseBrush = (Brush)this.TryFindResource(brushKey);


 


Whether you define your resources at the theme level or merge them at the element level depends on your scenario.  Here’s a summary of the things to keep in mind:


 


1)       If you create the resource dictionary at the theme level, you have to use ComponentResourceKeys as keys instead of strings. 


2)       Implicit style application does not occur on the theme level.  Suppose you want all the labels on your controls to have a certain style.  If you define the style in at the element level, you do not have to give the style an explicit key, the labels will use the style automatically.  This is not the case for resources at the theme level.  You must define a key and reference the style every place you want to use it.


3)       If you use XAML to merge resources at the element level, a ResourceDictionary is created each time you reference the shared dictionary to merge it.  To use a single instance of the shared dictionary, you have to write code.


 


The attached project defines contains two control libraries.  One library creates a ResourceDictionary in the Themes/generic.xaml file. The other library creates a shared ResourceDictionary and merges the shared dictionary with two custom controls in code. 


 

SharedResources.zip


Comments (4)

  1. Last month I explained how to use shared resources in a control library . This month I’ll create an example

  2. Ask Dr. WPF says:

    Dear Dr. WPF, We are running into some issues around application level resources when we attempt to put WPF task pane UI within Office. The primary issue is that the runtime host is not WPF i …

  3. jbe2277 says:

    The approach shown in this blog “Defining Resources at the Element Level” works fine at runtime. Unfortunately, it doesn’t work inside the Visual Studio WPF Designer (Cider). The Designer doesn’t load the code in the code-behind file and so the following code is never executed inside the Designer:

    public NumericUpDown()

    {

       this.Resources.MergedDictionaries.Add(

           SharedDictionaryManager.SharedDictionary);

       InitializeComponent();

    }

    Alternative approaches that work with the designer are described here: http://www.codeplex.com/CompositeExtensions/Thread/View.aspx?ThreadId=42919

  4. Siderite says:

    Hi, I have been trying for a day now, to no avail, to create a bunch of brushes in the theme then using them with DynamicResource in a custom control. What I did is this:

    – create the theme generic.xaml which contains styles (works)

    – add a dictionary to merge in generic.xaml to contain brushes used in the application (works)

    – make brushes have ComponentResourceKey keys (works)

    – make control use brushes as static resource (works)

    – make control use brushes as dynamic resource (DOESN'T WORK, the resource trace source says as much)

    – add in App.Resources dynamically a brush with the same key (works with dynamic resource, it changes the colors, doesn't work with static resource, as expected)

    So my problem is that I can't find any way to define the default values in the theme so that I can change them programatically in the application. How can StaticResource find the brush and DynamicResource not?!

    I must add that I've created a static class holding the component resource keys as properties that I then use in the xaml as {x:Static UI:ResourceScheme.ControlBackgroundKey} for example. My problem seems similar to this one: <a>stackoverflow.com/…/ only that if I replace the static property keys to the XAML markup for component resource key, it still doesn't work.

    Can someone please help me out here? :(