Tuesday, November 11, 2014

XAML Organization




We've worked on countless WPF and Silverlight projects over the past several years and throughout that time, we've refined both our process and the organization of our solutions.  We pass off front-end code to our client developers.  So clean, understandable organization is extremely important for an effective transfer of knowledge.

Most of the development teams that we work with are well versed with c# code, programming methodologies, and best practices.  But typically we find that XAML is not something that they care much about.  Due to this lack of interest folks tend to not put much up-front thought into how their Resource Dictionaries are organized, nor is there much in the way of guidance from Microsoft.  So then 3 months into their development cycle the application looks great from a code perspective, especially if the Model View ViewModel (MVVM) paradigm is followed, but digging into the various styles, templates, brush resources, etc… reveal a lot of problems.
...
...

Rule#1: One Style per Resource Dictionary

For all but the smallest, apps, you will want to follow this rule.  It is much easier to find a style within a directory than if it is buried deep inside of a gigantic "catch-all" Resource Dictionary.  It is very similar to the c# rule of one class per file.  Now there are exceptions to rule #1,  we do occasionally package up more than one style in a Resource Dictionary, but only if there is a tight pairing between styles such as a small supporting style that the main style needs.  A good example of this is the button style that a scrollBar uses for "Line up"/"Line Down" buttons.  We would package these styles together.

Rule #2: Resource Dictionary named to match contained style

Simple enough, if you have a named style called "HelpButtonStyle", name the Resource Directory "HelpButtonStyle.xaml".  If you have a nameless style that acts as the default for a control, name the Resource Dictionary the same as the TargetType, for example "ComboBoxStyle.xaml"

Rule #3: No resources directly in App.xaml (only ResourceDirectory merging)


Read more: Projekt202