All XAML dialects support a feature that is used mostly by accident, yet goes overlooked for its vast potential: Attached Properties. In simple terms, these are properties that can be arbitrarily attached to just about any object in the UI hierarchy and allow attaching data that needs to be associated and stored with those objects. In more sophisticated terms, Attached Properties are a feature that allows developers to extend UI objects with arbitrary features in very powerful ways.

But let's start at the beginning: In systems such as WPF (Windows Presentation Foundation) or WinRT (what the industry generally refers to as the “XAML Dialects”), UI elements and controls behave much like you would expect them to behave. This includes elements with properties that can be used to change the appearance or behavior of said elements.

What may not be obvious to the casual observer is that in XAML, these properties are slightly different from “normal” properties. These XAML properties are implemented as “Dependency Properties.” The main difference is that while properties in .NET are a language feature that combines a get/set pair of methods with some internally stored value (such as the text of a TextBox), Dependency Properties, while still being accessible through get/set, store their values in an external, highly optimized place.

Why such a difference? One reason is the matter of efficiency. Systems like WPF instantiate lots and lots of objects, all of which have lots and lots of properties. An efficient way is needed to store those properties, especially since many of those properties simply sit there with their default values (a scenario that received special efficiency tuning in the Dependency Property system). The second reason for Dependency Properties is that WPF (and other XAML dialects) requires features that standard properties don't provide. One of these is built-in change notification. Another is the ability to define further meta-data, such as what the default value is, or how the property is to behave in binding scenarios. And those are just a few features.

Fundamentally, the Dependency Property system is a way to first define a property and register it with the overall Dependency Property system, and then assign values to those properties, at which point the system maintains that value for each object. You can think of this system as an external table of named values that go with a certain object. In object-terms, this is a bit odd because the values that go with an object are not encapsulated in the object anymore. Nevertheless, this is a very useful and efficient system, which, to most users, ends up looking very similar to any other property system.

As a simple example, let's imagine a TextBox control that defines a new property to assign a security ID to each instance of the control. This hypothetical property could be used to identify the object uniquely and attach some security feature (such as making the control read-only based on certain criteria, which I won't further explore here).

The following code snippet shows how you could subclass the TextBox and add that property:

public class TextBoxEx : TextBox
{
    public string SecurityId
    {
        get
        {
            return (string)GetValue(SecurityIdProperty);
        }
        set { SetValue(SecurityIdProperty, value); }
    }
    public static readonly DependencyProperty
    SecurityIdProperty = DependencyProperty.Register("SecurityId",
        typeof(string), typeof(TextBoxEx), new PropertyMetadata(""));
}

Note that there are two parts to the definition of a Dependency Property. The property itself is defined as a static, read-only member of the class, which registers itself with the Dependency Property system by providing details such as the name, the type, the class the property goes with, and the default value (as well as other optional parameters). Then, there is a standard .NET property, which uses the GetValue() and SetValue() methods to store and retrieve the values from the Dependency Property system. This is what makes the property look like a normal property to the users of this system. (For this to work, the object must inherit from DependencyObject in some form, as every UI element does.)

As a result, you can now use the new object in XAML like this:

<my:TextBoxEx SecurityId="abc" />

In order to reference the new class, you must declare an XML namespace to point to the .NET namespace the class is defined in. In this example, I chose to call that namespace “my.”

Using this approach, you can now save the desired security ID into the table of values the Dependency Property system keeps. In other words, this value is now stored externally and associated with this TextBoxEx instance. You can now write some code that retrieves that value (either internally in that class or in some other place) and does something useful with it.

Using Attached Properties, I've been able to help many a customer simplify their projects greatly yet make them more efficient and flexible.

All this raises an interesting question: If you can externally store this property value with an object instance, then why can't you externally store arbitrary values and associate them with any object without the need to subclass an object? After all, the system seems to be a way to map named values to object instances (“store ‘abc’ as the security ID with this textbox”). And in fact, this is exactly what Attached Properties allow us to do. They're really just a special case of Dependency Properties (or looking at it from the other side: Dependency Properties are artificially restricted to store values for specific objects, but the overall system can do more).

A First Attached Property Example

To take the security ID example and turn it into an Attached Property, you first need a place to define the property. You still need a class for that. You could use a subclass of the TextBox class just like in the prior example, but I would like to make things a bit more generic and create an Attached Property that can be attached to any UI element, not just text boxes. After all, this kind of flexibility is one of the benefits of the Attached Property paradigm. For this purpose, I created a new class called “Ex.” Note that this class still needs to inherit from DependencyObject for the required functionality to be available:

public class Ex : DependencyObject
{
    public static readonly DependencyProperty
    SecurityIdProperty = DependencyProperty.RegisterAttached(
        "SecurityId", typeof(string), typeof(Ex), new PropertyMetadata(""));
    public static string GetSecurityId(DependencyObject d)
    {
        return (string) d.GetValue(SecurityIdProperty);
    }
    public static void SetSecurityId(DependencyObject d, string value)
    {
        d.SetValue(SecurityIdProperty, value);
    }
}

There are two main differences between this example and the previous one that defined a standard Dependency Property. One difference is that this example calls RegisterAttached() rather than just Register(). The other difference is that this example doesn't have a standard .NET property anymore, and instead, there now are static GetSecurityId() and SetSecurityId() methods. That's because you will never set these properties on the Ex object directly, but instead want to store this value with other properties. It wouldn't make sense to create a standard property at all.

You can now use this new Attached Property on any element you want. Consider these examples:

<TextBox my:Ex.SecurityId="a1"/>
<Button my:Ex.SecurityId="a2"/>
<TextBlock my:Ex.SecurityId="a3"/>

What happened here? How did the C# property definition all of a sudden enable you to do this? Well, this is just special syntax that XAML allows. Whenever you refer to another class' property within an element definition, XAML verifies that such a class (“Ex”) exists, with the defined property (“SecurityId”) available as a pair of static SET and GET methods of the required name. In this example, assigning this value calls the static Ex.SetSecurityId() method to assign the desired value and store it away for the specified object instance (the one the property appears to be set on, like the TextBox in the first line). You could argue that this is all syntax trickery, which is true, but it sure ends up as a very convenient system.

Attached Properties provide a much simpler and more flexible way to extend XAML than just about any other technique you may have heard of.

Now that you have these values stored away, you can use them for a variety of things. You could create control templates that pick up on this value for instance. Or, you could write code that accesses the value. The following code snippet goes through a parent container's list of child items and checks the SecurityId property:

foreach (UIElement child in Children)
{
    var id = Ex.GetSecurityId(child);
    if (id == "a1")
    {
        // do something significant here
        child.Visibility = Visibility.Collapsed;
    }
}

It's interesting to note how convenient and handy all of this is. First, you were able to create a property that is now available on any object. You didn't have to subclass all conceivable UI elements and then add this property. Instead, you created it only once. (There is no danger of naming conflicts or ambiguity; because the property is assigned to the Ex object, other classes that might define a property of the same name can't cause conflicts.) You were also able to use this property very easily on any type of UI element. You didn't have to check the type of the child element and then write special code for each and every one of the possible types. You also didn't have to create any interfaces. Instead, it's possible to handle all items generically. Furthermore, you don't have to worry about the property not being set, because at the very least, the call to the GetSecurityId() method returns the property's default value.

The following snippet shows an example of a TextBox control template that uses this new property (this particular example is a WinRT XAML example):

<ControlTemplate TargetType="TextBox">
    <Grid Background="White">
        <ScrollViewer x:Name="ContentElement" />
            <TextBlock Text="{TemplateBinding my:Ex.SecurityId}"
                       VerticalAlignment="Bottom"
                       HorizontalAlignment="Right"/>
    </Grid>
</ControlTemplate>

This is all nifty stuff. It's also something you may have inadvertently used before, since the different XAML versions use this technique extensively. For instance, if you are using a Grid layout element, you may have found yourself setting grid rows and columns on other elements:

<TextBox Grid.Row="4" Grid.Column="2"/>

So now you know how this works. (Some people think these properties are available for controls that are contained in Grid elements. This is not the case. You can set these attached properties regardless of whether an element is inside a Grid or not. It may not have any affect.)

Attaching Behavior

All of this is nice, but it doesn't quite reach the “it's magic” level of awesomeness yet. I would venture to guess that most developers never realize that there's quite a bit more to Attached Properties, yet I've only scratched the surface. Where things get really interesting is when the assignment of values goes along with added behavior.

There's a tiny gem of functionality in Attached Properties that provides a huge degree of control and power: When an Attached Property is set, a change notification method can be triggered. This change notification fires every time the property value changes and it passes the new value as well as a reference to the object the property value is associated with. This allows you to add any code conceivable, which is very powerful indeed.

Let's consider a simple example. All XAML dialects allow defining a Grid layout panel. Grids can have rows and columns defined. Here's an example:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="25"/>
    </Grid.RowDefinitions>

This is very useful. It's also very painful when you consider how much code it takes to set up this simple arrangement. Furthermore, this verbose nature makes it harder than it needs to be to create a style for the Grid that defines row heights or to data-bind the row definitions. Although it may sometimes be useful to have access to all kinds of details for row definitions (there are other properties to set on each row), in more than 99% of the cases, one just wants to set up the heights in the manner shown in this example. A simpler and more concise approach would be nice!

You can easily enhance this scenario by creating a new attached property. Here is the definition of that property:

public static string GetRowHeights(DependencyObject obj)
{
    return (string)obj.GetValue(RowHeightsProperty);
}
public static void SetRowHeights(DependencyObject obj, string value)
{
    obj.SetValue(RowHeightsProperty, value);
}
public static readonly DependencyProperty
RowHeightsProperty = DependencyProperty.RegisterAttached("RowHeights",
    typeof(string), typeof(Ex), 
    new PropertyMetadata("", RowHeightsChanged));

This is almost identical to the previous example. The main difference is in the very last line, where the meta-data is configured to call a RowHeightsChanged() method whenever the property value is changed. (More about that in a moment.) With this definition, you can now use the new property like so:

<Grid my:Ex.RowHeights="*,Auto,25">

Whenever this line of code executes, the RowHeights property is set, and the RowHeightsChanged() method is fired. This is where the cool stuff happens: The change-method receives the new property value as a parameter, as well as a reference to the object the property was set on (the Grid in this example). This may seem trivial, but the consequences are of utmost importance. It allows you to write whatever code you want that will react to the property change and then interact with the object the property was set on. It will do the vast majority of things you could do when subclassing, yet you never had a need to create or use a new or special Grid class.

In this example, you use the change-method to grab a reference to the Grid (the parameter is of type DependencyObject. You first need to cast it and make sure the cast worked, as people could set this property on objects other than Grids), parse the property value, and then add appropriate row definitions to the Grid object. Listing 1 shows the full definition of this Attached Property, including its change-method.

Listing 1: Attaching a simplified RowHeights property to a Grid

public static string GetRowHeights(DependencyObject obj)
{
    return (string)obj.GetValue(RowHeightsProperty);
}

public static void SetRowHeights(DependencyObject obj, string value)
{
    obj.SetValue(RowHeightsProperty, value);
}

// Using a DependencyProperty as the backing store for RowHeights.  
// This enables animation, styling, binding, etc...
public static readonly DependencyProperty RowHeightsProperty =
    DependencyProperty.RegisterAttached("RowHeights",
    typeof(string), typeof(Ex),
    new PropertyMetadata("", RowHeightsChanged));

private static void RowHeightsChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs args)
{
    var grid = d as Grid;
    if (grid == null) return;

    grid.RowDefinitions.Clear();

    var definitions = args.NewValue.ToString();
    if (string.IsNullOrEmpty(definitions)) return;
    var heights = definitions.Split(',');

    foreach (var height in heights)
    {
        if (height == "Auto")
            grid.RowDefinitions.Add(
                new RowDefinition{Height=GridLength.Auto});
        else if (height.EndsWith("*"))
        {
            var height2 = height.Replace("*", "");
            if (string.IsNullOrEmpty(height2)) height2 = "1";
            var numHeight = int.Parse(height2);
            grid.RowDefinitions.Add(new RowDefinition
            {
                Height = new GridLength(numHeight, GridUnitType.Star)
            });
        }
        else
        {
            var numHeight = int.Parse(height);
            grid.RowDefinitions.Add(new RowDefinition
            {
                Height = new GridLength(numHeight, GridUnitType.Pixel)
            });
        }
    }
}

Using this simple Attached Property, you have certainly made your life easier and the syntax associated with the creation of rows much more concise and easier to understand and maintain. But the advantages go beyond plain simplicity and convenience. For instance, the property is now also very easy to data-bind:

<Grid my:Ex.RowHeights="{Binding HeightDefinitions}">

For this binding expression to work, all you need is a string value to bind to, which could easily be exposed in a view-model or some other data context.

Another benefit is that this makes row definitions easily stylable. For instance, you could create this style:

<Style TargetType="Grid">
    <Setter Property="my:Ex.RowHeights" Value="*,Auto,25"/>
</Style>

Setting row heights on Grids is but one example, but I think you can see the potential this technique has.

Example: Fixing Text Boxes

There are quite a few things in the different XAML dialects that don't necessarily work the way you want them to. After all, Microsoft couldn't possibly think of everything, or have enough time to implement everything to satisfy everyone's needs. This means that developers often change things to their liking. One way to do this is through subclassing. This often works well, but it also has some issues.

For instance, let's say you would like to change a TextBox's behavior to select all its text when it receives focus. You may already be using hundreds or even thousands of text boxes throughout the application when that requirement arises. Furthermore, you may have different types of text edit controls that all have that same requirement.

With all that, creating subclasses of all the controls in question and then updating all the UIs to use those new controls is a lot of work. You may encounter other issues, such as there already being various subclasses of text boxes for other reasons. Now what?

Using Attached Properties, you can simply define a Boolean Attached Property called “SelectOnEntry” and create a change handler that's triggered whenever the property is set to true. In that handler, you grab a reference to the object, and subscribe to its GotFocus event so you can use it to set the selection. Here's the change handler for that property:

private static void SelectOnEntryChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs args)
{
    if (!(bool) args.NewValue) return;
    var text = d as TextBox;
    if (text == null) return;
    text.GotFocus += (s, e) =>
    {
        text.SelectionStart = 0;
        text.SelectionLength = text.Text.Length;
    };
}

As you can see, the actual code is quite simple and allows you to do most of the things you could do with subclassing a TextBox control (except for accessing and overriding protected members, that is, which isn't much of a limitation these days). The hardest part about all this is realizing that Attached Properties offer this kind of flexibility.

With this new property in place, you can now use the new property like this:

<TextBox my:Ex.SelectOnEntry="True" />

This is very cool, because you have now arbitrarily extended all TextBox controls with this new capability, which we can access simply by setting that property. (You could have made the code more generic to also handle other text entry controls.)

There is however one fly in the ointment: If you already have thousands of text boxes in use throughout the application, updating every single one of them to set this property is going to be quite painful and labor intensive. Luckily, there is a better approach! You have already discovered that you can style Attached Properties just like any other property in XAML. Therefore, you can create a style that sets this property for you:

<Style TargetType="TextBox">
   <Setter Property="my:Ex.SelectOnEntry" Value="True"/>
</Style>

If this style is put into a place that is accessible in the entire application (such as App.xaml or a resource dictionary that is globally accessible), this style automatically and implicitly applies to all TextBox controls. Therefore, all text boxes in the entire application will now select their text when they receive focus. How cool and easy is that?

Example: Fixing Password Boxes

At this point, you've seen how to arbitrarily store values with objects and then access them for things like security. You've seen how to add behavior that triggers when the value is set. You've also seen how that behavior can do advanced things like hook events that can trigger various things later. You've even seen how to use styling and binding for great effect. You can use this for a wide range of features limited only by your imagination. I can't possibly list all the scenarios I have used it for.

However, there is one more usage scenario I would like to point out, to give you some more ideas: In WPF, the PasswordBox control allows setting a Password through a property of the same name. The control very much behaves like a TextBox, except it shows only dots for each character typed so the password doesn't become visible. One problem with this control is that the Password property isn't bindable, since Microsoft chose to implement it as a regular property rather than a Dependency Property. This is very inconvenient in MVVM (Model, View, View-Model Pattern) scenarios (among others).

I wouldn't be telling you all of this if you couldn't fix this using Attached Properties. Listing 2 shows an implementation of the solution. An Attached Property called “Value” is used to provide a new, bindable property. (The extra parameters are passed to the meta-data to change the exact behavior for the binding mode as well as the exact timing of binding updates.) There is a change-handler for this new Attached Property that takes whatever the Value is set to and sticks it into the actual Password property of the PasswordBox the Attached Property is associated with. This means that you can now update the password box's Password property simply by setting the attached Value property.

Listing 2: Adding a bindable Value property as an Attached Property for PasswordBox controls

public class PasswordBoxEx : Control
{
    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.RegisterAttached("Value",
        typeof (string), typeof (PasswordBoxEx),
        new FrameworkPropertyMetadata("", ValuePropertyChanged)
    {
        BindsTwoWayByDefault = true,
        DefaultUpdateSourceTrigger = UpdateSourceTrigger.LostFocus
    });

    private static void ValuePropertyChanged(DependencyObject d,
        DependencyPropertyChangedEventArgs e)
    {
        if (_inPasswordChange) return;
        var passwordBox = d as PasswordBox;
        if (passwordBox == null) return;
        passwordBox.PasswordChanged += (s, e2) =>
        {
            if (_inExternalPasswordChange) return;
            _inPasswordChange = true;
            SetValue(d, passwordBox.Password);
            _inPasswordChange = false;
        };

        _inExternalPasswordChange = true;
        if (e.NewValue != null)
            passwordBox.Password = e.NewValue.ToString();
        else
            passwordBox.Password = string.Empty;
            _inExternalPasswordChange = false;
    }

    private static bool _inPasswordChange;
    private static bool _inExternalPasswordChange;

    public static string GetValue(DependencyObject obj)
    {
        return (string)obj.GetValue(ValueProperty);
    }

    public static void SetValue(DependencyObject obj, string value)
    {
        obj.SetValue(ValueProperty, value);
    }
}

Furthermore, there is an event handler hookup that listens to changes in the PasswordBox control. This handler picks up changes in the Password properties and syncs them back into the attached Value property. This is important, since you need to make sure that the Value property is updated when the user types a password, so whatever is bound to the Value property can be updated properly. (There also is a simple check to make sure the whole thing doesn't become cyclical.)

And that's it! You just fixed the PasswordBox control!

Conclusion

Attached Properties are a relatively trivial feature in XAML. They are simple syntactical sugar for associating named values with objects. Due to this simplicity, the feature often goes overlooked. However, due to some implementation details (such as having a changed-handler that provides access to the full object), Attached Properties end up as one of the most powerful features in XAML. I've helped many customers with WPF and other XAML projects that suffered from exceptional high complexity, with very sophisticated features (such as global event systems) used to implement relatively simple features. Using Attached Properties, I was able to greatly simplify these projects (such as the select-on-entry feature for text boxes) and make these projects not just easier to understand and maintain, but in many cases also improve performance.

The only downside to Attached Properties is that they are somewhat harder to discover than regular properties. This is a factor that you may want to consider, but in my experience, many alternative techniques (such as subclassing or global event handlers) are no easier to discover.

I have used Attached Properties as described here with great success. In fact, CODE Framework (CODE Magazine's free and open-source business application development framework) uses the concept quite heavily and you can explore it for further inspiration. (See the CODE Framework sidebar for more details). I'm confident that you will see similar success with this approach.