Better XAML By FARR: Resource Dictionaries Vs User Control Resources
A while ago I had a debate with my co-worker on when to put a resource in a User Control (whether it would be in XAML or in code behind) or put that resource in a Resource Dictionary. We had this debate because we initially put all our resources in Resource Dictionaries and as our application became more modular this would become a problem when we only want to update a particular section’s resource. Since all our resources were in the same location (our shell project) if a change was necessary, the shell project would also need to be updated. I debated that it was nice to have all resources centrally located. He claimed there were times a resource should be centrally located (when its accessed by multiple controls in multiple projects) and times when it should be directly tied to a particular control. After a while of discussing back and forth the pros and cons of both, I finally sided with him on the following criteria.
- Resource Dictionary
- If multiple controls in a solution need to access a resource then it should be put in a Resource Dictionary
- User Control Resource
- If a resource is specific to that User Control (for example a specific animation that is only performs within a specific User Control) then it should be put in the User Control’s Resource section.
These rules may be simple, but as an application grows it is very easy to overlook this scope for resources and especially since resources aren’t the easiest to debug, this can easily create chaos in future development.
So are there cases where this scope may not work for an application? (Where I was right?) Sure! When discussing this topic with one of our designers, he said it would be much easier for him to update all resources if they were in a centralized location. Designers using Expression Blend do not really want to go through an entire application to find assets they need to update. As we move further towards the direction of designer/developer collaboration, we must change our development techniques somewhat to coincide with a designer’s techniques.
In conclusion, As a developer, I have become fan of specifically defining resources as there is no reason for all controls to have access to them, however I do understand there may be a need to have a centralized location for resource. Being consistent is the most important thing. Whether you divide resources into sections or keep them all in the same Resource Dictionaries, you must stay consistent with the scope you define.