If you search the net for a skinnable application, you get a lot of answers and pages that seem to hit the spot right on. If you are looking for a skinnable control library, though, the hit count drops considerably. This post is about my adventures with resource keys and the solution for a problem that has plagued me for more than a day of work, plus some weird behaviour that I have as yet no explanation for.

The article is pretty long, so here is the short and dirty version:
  • Do not use Colors as dynamic resources, use Brushes
  • If you want to use resources from a theme dictionary outside the assembly, you must give them keys of the type ComponentResourceKey
  • The type you use in the constructor of the ComponentResourceKey class or in the markup extension of the same name must be in the same assembly where the resource is!


The scenario is as follows:
  • there is an application that needs to change some of its visual characteristics dynamically during run time
  • the application uses a custom control library
  • other applications/modules should use the same themeing mechanism
  • other applications will use the same control library


The solution seemed simple enough:
  • create a static class to hold the string keys for the resources I want to define dynamically
  • create a shared resources dictionary in the controls theme, using those keys
  • use the shared dictionary in the controls theme
  • create another shared resources dictionary in the applications, or use only the ones already defined in the control library
  • use the application shared dictionaries in the application styles
  • programatically add/remove resources directly in Application.Current.Resources to override the already defined resources


I have tested this solution in a not very thorough manner and found it working. Of course, some of the problems needed solving.

The first issue is that theme level resources are not found from outside the assembly unless defined using a ComponentResourceKey as the key of the resources. This special class receives two parameters in the constructor: a type and an object that is a "regular" resource key. So instead of using a string, as one would probably use in an application style, you use a component resource key that receives a type and that string. A small test confirmed that a resource is not found at the application level using FindResource if only defined with a string as key and that it is found if using a ComponentResourceKey.

The second issue was that in order for a resource to be dynamically changed at runtime it needed to be defined as a DynamicResource, not a StaticResource which is only resolved at compile time. Not a huge problem. However, if one has defined some brushes in the control library and then referenced them in all the styles, then it would also work to redefine those brushes to use colors dynamically, and then all one has to do is change the colors. That would also prove advantageous if one needs a variety of brushes using the same colors, like gradients or some lighter version of the same color.

This leads to Problem number 1: Dynamically changing Color resources worked for foreground brushes, for background brushes, but not for border brushes! So you have a textbox and you define Background, Foreground and BorderBrush properties using StaticResource on brushes that themselves define their Color as a DynamicResource. You change the colors (adding new resources at the application level of the type Color) and you see the Background and Foreground changing, but the border staying unchanged.

I have no idea why that happened. Some information that I got researching this problem was related to Shared resources, but changing the shared status of brushes or even colors to true or false did not change anything. Another idea was that his was related to their Frozen status but, as there was no difference between the Foreground and BorderBrush brushes (I even used the same brush at the same time on both properties), I've decided that it wasn't the case.

BorderBrush is a dependency property belonging to the Border element, while Foreground and Background belong to the TextElement and Panel elements, respectively, and other elements add themselves as owners to them. In the case of the Border element that I have tested this weird behaviour on, BorderBrush is its own dependency property, while Background is the Panel.BackgroundProperty. I also thought that it may have something to do with FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender, but both properties are registered with this flag.

After some searching, I found that the Border element caches internally Pen objects that are used to render the different border sides. They use the same brush as the border, though, and so, even if this is the best candidate for the cause of the problem, I still don't know what the hell was going on.

The solution for this problem was (to my chagrin) to use the brushes themselves as dynamic resources. Well, it was a setback, seeing how the resources I want to change are colors and now I am forced to create brushes and, thus, stain this process with the responsibility of knowing what kind of brushes are needed for my controls and applications, but I could live with it. After all, that was all WPF stuff, so I could separate it at least from the static class holding the keys of the characteristics I wanted to change dynamically.

Problem number 2: using as a key in XAML a class with a long name which uses a constructor that receives a type and a static constant/property of a class is ugly and unwieldy. The solution for this problem was to create another static class that would hold the keys for the brushes. Each brush would have a property in the class that returns a ComponentResourceKey object that uses the classes own type as the first parameter and the constant string key from the static string key class.

That effectively changes stuff looking like {DynamicResource {ComponentResourceKey TypeInTargetAssembly={x:Type UI:ResourceScheme},{x:Static UI:ResourceScheme.ControlBackgroundKey}}} to {DynamicResource {x:Static WPF:ThemeResources.ControlBackgroundBrushKey}}. Still a mouthful, but manageable.

Problem number 3 (the big one): it doesn't work! The brushes I so carefully created in the theme are not getting set in the controls, not the mention the application. What confounded the issue even more is that if I changed DynamicResource to StaticResource in the control templates I would see the brushes rendered correctly. I wouldn't be able to change them dynamically afterwards, but how come StaticResource works and DynamicResource doesn't!? Stranger still, adding/removing resources with the same key in the application resources dictionary (the mechanism that was supposed to dynamically change the aspect of the application) worked! Everything was working perfectly, and only the default brushes defined in the theme were not loaded!

The solution for this was (after hours of trial, error, googling, suicidal thoughts and starting all over again) to use a type from the control library in the ResourceComponentKey constructor! You see, I had placed both static key classes in a separate assembly from the control library. Moving the WPF related resource key class in the control library fixed everything!

Now, you may be wondering why that worked, and so do I. As I see it, if you define a template and a brush in a theme and the template is loaded and applied, then the brush should also be loaded. If FindResource did not find the brush, then it must be that either the brush was not loaded due to some internal requirements of the ResourceComponentKey class or that it was loaded and then the key I was using was different from the one I was using when asking for it or, as Akash Kava tried to explain to me on StackOverflow, it will only find in the resource dictionaries of its own logical parental tree.

I have dismissed the second option, as the ComponentResourceKey has an Equals override that simply compares type and key. There cannot be two instances of the same type and the key is a string constant, so there should be no ambiguity on whether two resource keys are equal.

What remains are that either the ComponentResourceKey class messes things up or that the resources using resource keys are placed in "logical trees" based on the target type of the ComponentResourceKey. I have looked for the usages of the ComponentResourceKey class and all I could find was something in a BaseHashHelper that seemed related to ItemsControl or CollectionView, so I don't think that's it. I also looked at the implementation of FindResource, but found nothing that I could understand to cause this.

As a funny side note, as I was going about this task I was trying to get inspiration from the way the SystemColors class worked. The resource keys related to colors that were returned were not of the type ComponentResourceKey, but of SystemResourceKey, both inheriting from ResourceKey nonetheless. I have noticed no significant piece of code in the (of course internal) SystemResourceKey class, however I did find code in FindResource that checked if the key is of type SystemResourceKey and did something with it. Nice, Microsoft! However, that was not the cause of the problem either.

After knowing what to look for, I did find on the Microsoft article about the ComponentResourceKey markup extension that The TypeInTargetAssembly identifies a type that exists in the target assembly where the resource is actually defined. In the article about the ComponentResourceKey class, they say If you want an easily accessible key, you can define a static property on your control class code that returns a ComponentResourceKey, constructed with a TypeInTargetAssembly that exists in the external resource assembly, and a ResourceId. Too bad they hid this information in the Remarks section and not in the definition of the Type parameter.

Congratulations if you have read so far! You must be really passionate about programming or desperate like me to find an answer to these questions. I hope this article has enlightened you and, if not, that you will find the answers and then get back to me :)

Comments

Be the first to post a comment

Post a comment