Just another WordPress.com weblog

A number of people that I’ve spoken to about Windows Presentation Foundation have asked about coding standards, guidelines and best practices for working with it and XAML. Whilst WPF is still a relatively new platform, and it will take time for real standards to emerge, I thought I would have a go at making a list of the ones I follow currently. These are based off experience with the WPF projects I’ve worked on so far, so a number of them might not be suitable for everyone, but hopefully they’ll serve as a good starting point.

I’ve broken them up into XAML Conventions and Resource Organization.

XAML Conventions

XAML is still XML and so the majority of the XML formatting standards that you use will still apply. That said, here’s a couple of extra ones I’ll throw in on top:

1. Use x:Name instead of Name

While they both do the same thing, Name can only be used for some elements, where x:Name will work for any element (except elements in a resource dictionary). When you’re looking through a long list of attributes on an element, attributes starting with an "x:" prefix tend to be a little easier to spot. To make it easy to find the name of an element without looking twice, I always stick to x:Name.

2. Place the first attribute of an element on the line underneath the element name

Of course, this only applies when you’re setting a number of attributes. If you decide to wrap the attributes onto the next line, like this:

This places all of your attributes at the same standard indentation level, and stops them from being more indented than their child elements. Also, if you do decide to wrap one element onto a newline, wrap all of them – don’t go half way.

3. Use DynamicResource sparingly

I think I have used the "{DynamicResource ...}" markup expression once in my entire time with WPF. The "{StaticResource ...}" expression does almost the same thing, but has a lot less overhead. The "Dynamic" part of DynamicResource means that the value of the resource may change (for example, by changing the resource dictionary through code), and because of this WPF has to add a load of hooks to detect these changes and act accordingly. Since there are very few situations where you would want to change a resource dynamically at runtime, stick with StaticResource unless you know you need DynamicResource.

4. If you ever draw a line one pixel thick, use SnapsToDevicePixels

This article on MSDN explains it. If you declare, say, a Border with a 1-pixel thick edge around it, the WPF virtual pixel rendering engine may sometimes smooth it, drawing it half over one pixel and half over the other. While this is often great for many shapes, on a 96 DPI monitor (the standard) it can look pretty obvious and often makes the element look out of the ordinary. I’ll usually declare a Style resource that sets this property automatically for all Border elements.

5. Give your root element a name

As I explained in my Binding Oriented Programming post, I give the root element of all of my XAML files an "x:Name" of "_this", or more recently, "PART_this". By doing this, I can refer to properties on the object from my markup, rather than having to explicitly set the value of my XAML elements from code.

6. Pick a Naming Convention for Elements

When you apply an x:Name to something, try to be consistent. In some projects I’ll use an "_" prefix, and in others I’ll use "PART_". The PART_ prefix, from memory, is used in a lot of the default styles that inbuilt WPF elements come with, such as the default style of a Button. If I see an animation that is being applied to an element called PART_ScheduleItemOuterBorder, it’s going to be a lot easier to find and understand than if it were named "myBorder", "border1" or "MyBorder". While prefixes are generally a bad thing to use in code, in markup they do make things much easier to locate.

UPDATE: It was correctly pointed out to me by a few people that the PART_ prefix wasn’t really intended to be used for all element names. Lately I’ve just been sticking to a single underscore as my prefix.

7. Merge resources at the Application level

When using merged resource dictionaries, it can be tempted to reference the resource XAML files from each Window rather than at the root Application XAML file. This can create extra work in initializing the dictionaries, so it is generally recommended not to do this.

8. Use DependencyProperties on DependencyObjects

When you have user controls of other objects that derive from DependencyObject, use DependencyProperties instead of normal CLR properties an INotifyPropertyChanged. This creates no confusion as to how properties should be monitored.

Resource Organization

As your WPF projects grow larger, you’re going to start to get a lot of resources and you’ll need to move them out of "App.xaml" (which, while we’re on the subject, I always rename to "Application.xaml"). But how do you organize them? Here’s what I use.

1. Structuring Resources

I think there are two different types of XAML files in any system:

Functional XAML files – these are usually Windows, User Controls, or Pages

Resource XAML files – these are usually Resource Dictionaries or your App.xaml file

Resource XAML files can be subdivided even further:

Generic Resource XAML files – these contain things that are used throughout the application. Brushes, ImageSources, some Styles and Converters are good candidates here.

Now, you’re probably aware that you can put resources within the XAML of Functional XAML files, such as in a Window.Resources element. I’ll often do this to start out with, but eventually I find it easier to move the specific styles and resources for a given Window or User Control into it’s own XAML file. This way, my "MainWindow.xaml" might define the structure of the Window, while "MainWindowResources.xaml" might contain the styles and resources that are specific to that Window but won’t clutter up the structural markup.

So, an example project structure could look something like this:

WpfBankingApplication/

/Shared/ – a folder that contains resources shared throughout the entire application

/Converters/ – a folder that contains a list of generic C# IValueConverters, such as a DateTime formatting converter or a string formatting converter

/HomeLoans/ – folder for the "home loans"-specific functionality of the application

/HomeLoanEntryWindow.xaml – a functional XAML file with the structural definition of the Home Loan Entry window.

/HomeLoanEntryWindowResources.xaml – a resource XAML file with the styles, control templates, custom brushes and other resources used by the Home Loans Entry window.

This structure keeps all of our XAML files small, and makes it pretty obvious to developers where they should place bits of functionality. Aim to keep each XAML file to less than a couple of hundred lines of XAML – 400 lines is probably the maximum I’d allow it to grow to. If they go beyond that, it’s probably time to split them up again.

2. Resource Naming Conventions

The biggest issue with using multiple resource XAML files is figuring out where a specific style or resource comes from. In C#, we can move our mouse over a type name and Visual Studio will tell us where the class is defined, and we can even right-click it and "Go to definition…" in order to go right to it. Unfortunately, the same can’t be done with things in XAML, though that’s a good idea for an add-in :)

To aid me in figuring out where something comes from, I employ a naming convention (again). The rules are simple. Notice in the project structure above that all of the Resource XAML files are suffixed with "Resources.xaml".

Any resources or styles declared in an "XYZResources.xaml" file gets a prefix of "XYZ_". So, if I declare standard light blue SolidColorBrush in BrushResources.xaml, I’ll name it "Brush_LightBlue". This means if you ever see markup like this:

Any resources or styles declared in a Functional XAML file, such as "HomeLoansEntryWindow.xaml", gets a prefix of "Local_". This is because these resources won’t be referred to outside of the XAML file they’re declared in, so if you spot the "Local_" prefix you can interpret it as "in this file".

That’s it!

They’re all the ones that come to mind right now. If you’re looking for other resources on XAML best practices and guidelines, check out the following resources:

WPF Performance Q & A by Tim Cahill. This is also a great discussion of WPF’s retained scene rendering mode versus GDI+ and DirectX’s immediate mode, what it is, why it makes a difference and what you can do to avoid problems with it.

[…] guidelines by Paul Stovell I just discovered that Paul Stovell posted a set of XAML and WPF coding guidelines.Â Â I really like hisÂ advice on resource organization.Â He provides a scalable way to structure […]

Excellent post. I wholehearted agree with everything separating the window specific resources into their own files, like HomeLoanEntryWindowResources.xaml.

There are several reasons why I keep window-specific style resources in the same file with the structural xaml. In Expression Blend, if the resource is on the same window xaml file, you can modify the style and see the result right away. If you edit resource for the style on a separate resource xaml file, you don’t get to see the change as you’re changing it. A second reason is that it adds more bloat. The number of xaml pages in the project is multiplied by two. Also if some pages have their own styles and others do not, it can be hard for developers new to WPF to understand the distinction why some windows have windownameResources.xaml and others do not.

I’ve been considering writing WPF guidelines for my firm too (I work for Siemens), and you beat me to it ;-) Congrats. I will shamelessly (but with your agreement) reuse them in our project. Possibly we will extend them, in which case I’ll notify you.

I have a remark to guideline 3: DynamicResource can actually speed the loading of an application up. You see, StaticResource are always evaluated when the application starts (when the XAML is parsed). DynamicResource, OTOH, is only evaluated when needed. In some cases, it may never be evaluated at all (for example in a trigger, if it is never triggered).

I think that guideline number 3 should be modified to integrate the comment above. Warning users against using DynamicResource is fine, but there are situations where it makes sense!

[…] XAML and WPF Coding Guidelines: A great starting point if you’re looking for coding guidelines in regards to XAML and WPF. In the future, there are going to be many more defined guidelines as the technology evolves, but for now this article by Paul Stovell should suffice plenty. […]

[…] helps us transfer from designer to developer the burden of enforcing a coding guideline like the Stovell Conventions, and lets designers focus instead on being creative with Blend. (Relevant aside: I really like […]

I agree with adding a dot before the Resources in resource file names. At one point I was hand-modifying projects (in Notepad) to make files like that explicitly dependent on their associated files, so that they would appear in the IDE like this:

– MainWindow.xaml
MainWindow.xaml.cs
MainWindow.Resources.xaml

However I’ve never felt very comfortable with that approach. Anyone know if there is any easy way to do this from the IDE?

Why a person would go through all the effort to publish a blog which results in unreadable content continues to amaze me.

Unfortunately, this blog is another example showing why something as simple as HTML in the hands of a moron talking about XAML is just as ridiculous as it became obvious when Flash was first used by the same group of morons who don’t know a damn thing about color contrast as it pertains to unreadable text in images used when writing technical documents.

It not only shows you are an incompetent it also says you are lazy and produce poor quality work. Me also an illiterate.