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:

<StackPanel DockPanel.Dock="Top" Orientation="Horizontal"
            Margin="3">
    <Button>

Change them so that the first attribute is on a new line, and put the closing angle bracket on its own line as well, like this:

<StackPanel
    DockPanel.Dock="Top"
    Orientation="Horizontal"
    Margin="3"
    >
    <Button>

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.
  • Specific Resource XAML files – these contain resources for a specific Windows, Controls or Pages.

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
      • /Images/ – contains all the raw image files (.PNG, etc.)
      • /BrushResources.xaml – solid brushes, linear gradient brushes and drawing brushes
      • /ConverterResources.xaml – allows us to reference any of the converters by merging our resource dictionary with this file, rather than re-declaring our converters every time
      • /ImageResources.xaml – as above, allows us to declare an ImageSource once and reference it from anywhere.  
      • /TextResources.xaml – styles applied to textual elements (Hyperlinks, TextBlocks, etc.)
      • /ControlResources.xaml – styles applied to specific types of controls, like perhaps custom-skinned Buttons or TextBoxes.
    • /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".

  1. 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:
    <TextBlock
        Style="{StaticResource Text_ContentHeaderText}"
        Margin="3"
        >
        Welcome!
    </TextBlock>

    You’ll know precisely where it comes from.

  2. 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".
    <TextBlock
        Style="{StaticResource Local_ContentHeaderText}"
        Margin="3"
        >
        Welcome!
    </TextBlock>

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:

  1. 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.
  2. Maximizing WPF 3D Performance on Tier 2 Hardware. Most of this applies to 2D WPF performance as well.
  3. WPF Globalization and Localization best practices. Some of this applies even if you aren’t writing a globalized application.
  4. Optimizing WPF Application Performance. The place to go for WPF performance guidance on many areas. The data binding section is my favourite.
  5. Windows Vista User Experience Guidelines. The official UX guidelines for Windows Vista.

What guidelines, standards or practices would you add to this list?

About these ads

Comments on: "Article: XAML and WPF Coding Guidelines" (40)

  1. Thank you for your advices. I am starting with WPF and I am very interested by these kind of post.

  2. Paul Stovell: WPF Coding Guidelines

    Paul Stovell has a list of guidelines he is recommending. Looks like a bunch of good ideas. Go tell him

  3. Appunti di WPF: WPF Coding Guidelines

    Appunti di WPF: WPF Coding Guidelines

  4. guidelines pour WPF

    Vous cherchez des bonnes pratiques pour coder en XAML, Paul Stovell s’est lancé dans l’écriture d’une

  5. WPF Guidelines

    Jeg faldt lige over Paul Stovells WPF coding guidelines . Ser ud som om han har fat i noget :)

  6. [...] 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 [...]

  7. Стандарт кодування для XAML

    Більш ніж код з нестандартним форматуванням, я ненавиджу код в якому декілька форматувань. Мабуть багато

  8. [...] PaulStovell.NET » XAML and WPF Coding Guidelines (tags: wpf .net xaml silverlight) [...]

  9. Excellent post, very good for newbies like me.

  10. WPF: Guía de codificación para WPF y XAML

    Paul Stovell, MVP en Client Application Development de Australia, ha publicado en su blog una pequeña

  11. WPF: Guía de codificación para WPF y XAML

    Paul Stovell, MVP en Client Application Development de Australia, ha publicado en su blog una pequeña

  12. [...] sourceforge) dostÄ™pny jest program pomagajÄ…cy opracowanie Help’a – Package This. Paul Stovell na swojej stronie zamieszcza pierwsze, nieoficjalne zalecenia dotyczÄ…ce standardów kodowania [...]

  13. EXCELLENT set of guidelines. I can definitely see the benefit of doing that. I already use a few of them in my code, it’s good to see validation from another developer!

  14. 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.

  15. typo in my last post. I meant to say:

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

  16. Hi Paul,

    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!

    Please contact me per email if you want to discuss this.

    Greetings,
    Laurent (also a recent MVP, congrats on yours ;-)

  17. [...] My XAML and WPF Coding Guidelines [...]

  18. [...] PaulStovell.NET » XAML and WPF Coding Guidelines [...]

  19. I have visited your site 533-times

  20. I could not find this site in the Search Engines index

  21. This would make for an awesome community-authored wiki.

    How about using jottit?

    http://wpf.jottit.com/

    http://xaml.jottit.com/

    ?

  22. Fantastic post! I really like the directory layout and naming conventions you’ve come up with. It makes everything very organized.

  23. I changed my mind on organizing resources into separate resource dictionaries. Blogged about it here: http://blogs.vertigo.com/personal/alanl/Blog/Lists/Posts/Post.aspx?ID=23

  24. [...] for guidlines for XAML and WPF should have a look at Paul Stovell’s blog. He provides some XAML and WPF Coding Guidelines which are worth reading for WPF [...]

  25. [...] Paul’s guidelines I created a “Converter” folder in my [...]

  26. Paul, looks good, but perhaps you could change the naming conventions for the resource files to put a period between the name and the Resources bit?

    MainWindow.Resources.xaml

    This seems to fit better with the ‘partial’ class naming convention, and would easily allow you grep for all the dependent files for MainWindow.

  27. Excellent resource you\’ve got here!!! Will definately be back!!!d

  28. thank you!
    can you please give us an idea how to make a data acess layer with linq to sql and wpf. I mean what kind of design should that be.
    Thanks in advance

  29. [...] 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. [...]

  30. Thank you for the coding tips and I found it also useful to read through the posts by folks, the DynamicResource post was correct. At times it can actually be a better route to go.

    Lots to learn for all of us… can’t say I will get bored anytime soon.
    :-)

  31. [...] 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 [...]

  32. [...] WPF Coding Conventions: The coding guidelines I use for WPF are a riff on Paul Stovell’s XAML and WPF Coding Guidelines. [...]

  33. 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?

  34. Clinton Gallagher said:

    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.

  35. [...] my WPF and XAML Coding Guidelines page (which I’ll be updating soon) I discussed a little rule I follow to keep my markup [...]

  36. [...] 2. XAML and WPF Coding Guidelines [...]

  37. Thanks for the guidelines, since Iam a beginner, but I woul like some resource on TreeView.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Tag Cloud

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: