Binding To Attached Properties

This post demonstrates a couple of different ways to bind to attached properties in WPF.

First, here's the code for the attached property that will be used in the demonstrations below. In this code, an attached property named Foo is defined within the Demonstration class. The attached property can be attached to any DependencyObject.

public static class Demonstration
{
    public static readonly DependencyProperty FooProperty = 
        DependencyProperty.RegisterAttached("Foo",
        typeof(string), typeof(Demonstration),
        new PropertyMetadata(default(string)));

    public static void SetFoo(DependencyObject element, string value)
    {
        element.SetValue(FooProperty, value);
    }

    public static string GetFoo(DependencyObject element)
    {
        return (string)element.GetValue(FooProperty);
    }
}
The Foo attached property

The example's DataContext has been set to this in the constructor.

DataContext = this;

In XAML

The code in this example will bind the Foo attached property to the Title property in XAML. Note that the namespace local is set to the DemoApp namespace. That's because the Demonstration class that defines the attached property is located there. In this case, no binding source has been provided, so the DataContext will be assumed as the binding source.

xmlns:local="clr-namespace:DemoApp"
Title="{Binding Path=(local:Demonstration.Foo)}"

In Code-Behind

Here's how to do the same thing in code-behind. This specific example assumes that this is a System.Windows.Controls.Page instance. Similarly, no source has been set on the binding, so the DataContext will act as the source.

var binding = new Binding
{
    Path = new PropertyPath("(0)", new object[] { Demonstration.FooProperty })
};
BindingOperations.SetBinding(this, Page.TitleProperty, binding);