The blog of dlaa.me

Breaking up (lines) is (not) hard to do [Tip: Put XAML attributes and elements on multiple lines so the markup is easy to read and work with]

Tip

Put XAML attributes and elements on multiple lines so the markup is easy to read and work with

Explanation

The last few tips have dealt with DependencyProperty issues. Now it's time for something completely different: XAML. While it's nice to pretend XAML editing can all be done in a design tool like Visual Studio or Expression Blend, I've always felt that XAML should be pleasant for people to work with, too. Therefore, it's worthwhile to establish a common approach to XAML formatting. What I find works well is to put attributes and elements on separate lines with a single indent for continuations and nesting. (Aside: I make an exception for elements with a single attribute to keep simple things compact.) I also tend to order properties according to importance, starting with the most significant ones and ending with the least. I consider the x:Name of an element to be the most important, so it typically comes first. Attached properties also rank high in my book and are usually next. After that, I tend to list common properties (ex: ContentControl.Content and TextBlock.Text) first and formatting properties (FrameworkElement.HorizontalAlignment and .Margin) closer to the end. In addition to keeping lines short and easy to read, this approach is very revision control-friendly - by which I mean that edits, adds, and removes all show up unambiguously. Sometimes people forget that markup is code, too - please treat it with the same respect and discipline. :)

Good Example

<Button
    x:Name="TheButton"
    Grid.Row="0"
    Content="Click me"
    Click="TheButton_Click"
    HorizontalAlignment="Center"
    Margin="10">
    <Button.Background>
        <SolidColorBrush Color="Pink"/>
    </Button.Background>
</Button>

More information