For the longest time I knew what Attached Properties in Xamarin.Forms were – the most famous example being setting a control’s position within a Grid …

<Label Text="I'm attached!" Grid.Row="1" Grid.Column="2" />

… but to be honest, I just didn’t care how the Grid.Row and Grid.Column or any attached properties worked behind the scenes. They were one of those things that as long as they worked – I didn’t care if I knew anything else about them.

I even knew I could use them to bind Commands to events that don’t work with Commands. And I heard rumors I could do cool things with Effects with them. But still, I didn’t care.

But I finally took the time to sit down and understand them … and wow am I glad I did! Attached properties are extremely powerful and they let you do some seriously cool stuff from XAML (or C# if you’re still into that).

What Are They?

Attached Properties allow properties from one object to be “attached” and set from another object. So in the ubiquitous Grid example – a Label can set the Grid’s properties – within the Label’s XAML declaration. Or as the official Xamarin documentation refers to it:

An attached property is a special type of bindable property, defined in one class but attached to other objects…

There’s a key word in that definition above that gives Attached Properties all of their power … “bindable”. Because they are bindable – they essentially provide a means to let one view to communicate with something else. Like another a view, or another class… like an Effect.

Creating an Attached Property

Creating an Attached Property is much like creating a normal bindable property. In fact, the only difference is that you use the BindableProperty.CreateAttached function instead of BindableProperty.Create. Check out my post on Custom Bindable Properties for a deep dive into the creation process.

I do want to touch on some of the required and important parameters however of the BindableProperty.CreateAttached function.

string propertyNameThe name of the attached property
Type returnTypeThe data type the attached property will be returning
Type declaringTypeThe class declaring the bindable property
Object defaultValueThe value of the property should nothing be assigned to it
BindingPropertyChangedDelegate propertyChangedA ha! This is an important one – gets called whenever the value changes

Everything there is pretty standard… but the cool part of those parameters is the propertyChanged delegate … it’s signature receives the view it is attached to – the old value of the property and the new value of the property. So keep that in mind … that’s the key to the power of Attached Properties.Using the CreateAttached function is the first step in creating an Attached Property (and make sure you name the variable you store the return from that function in so it ends with the word Property).

There are two more steps in creating an Attached Property – in addition to creating the BindableProperty you also have to create the getter and setter for it. And they have to follow a naming scheme. Using the propertyName parameter’s value from the BindableProperty.CreateAttached statement – the getter and setter must be: GetpropertyNameProperty and SetpropertyNameProperty.

Here’s an example that may make things clearer:

public static readonly BindableProperty HasBorderProperty = 
    BindableProperty.CreateAttached("HasBorder", typeof(bool), typeof(BorderEffects), false,
                                    propertyChanged: HasBorderChanged);
public static void SetHasBorderProperty(BindableObject view, bool hasBorder)
    view.SetValue(HasBorderProperty, hasBorder);
public static bool GetHasBorderProperty(BindableObject view)
    return (bool)view.GetValue(HasBorderProperty);

Notice that the parameter being passed into both the getter and setter is a BindableObject. That means only things that derive from BindableObject can have Attached Properties added to them.

That’s it – you’ve now created an Attached Property! You can go ahead and put it in the same class that will host the the property, or it can be in its own static class as well.

Creating these is kind of anti-climatic isn’t it? Well, that’s because I haven’t answered the big question yet … what are they good for?

What Can Attached Properties Do For Me?

This is where the fun starts. First off – I want to thank David Britch from Xamarin for all of the code examples in Xamarin’s documentation. Without, I wouldn’t have been able to fully grasp Attached Properties full potential.

So – let’s say you have a command in your view model and you want to tie it to an event on a control that doesn’t support commanding. Like the Completed event on the Editor class. A very easy way to do this is to create an Attached Property of an ICommand type.

Then – with the help of the propertyChanged delegate – the function that gets fired when the Attached Property changes value – we can setup an event handler on the Editor’s Completed event .. because the object the Attached Property being set on is passed in, and then invoke the Command in the Attached Property’s backing store every time the event gets fired.

public class EditorAttached
    public static BindableProperty CompletedCommandProperty =
        BindableProperty.CreateAttached("CompletedCommand", typeof(ICommand),
                                    typeof(Nullable), null, propertyChanged: HandleChanged);
    public static ICommand GetCompletedCommand(BindableObject view)
        return (ICommand)view.GetValue(CompletedCommandProperty);
    public static void SetCompletedCommand(BindableObject view, ICommand cmd)
        view.SetValue(CompletedCommandProperty, cmd);
    static void HandleChanged(BindableObject bindable, object oldValue, object newValue)
        var editor = bindable as Editor;
        if (editor == null)
        editor.Completed += (sender, e) =>
            var s = sender as Editor;
            var command = GetCompletedCommand(s);

Then to consume it:

<Editor Grid.Row="0" local:EditorAttached.CompletedCommand="{Binding FinishEditing}" />

Cool! So any event that a control has can be bound to a Command! For more on “Attached Behaviors” check out this article.

It gets even better with Effects! Here the general workflow is to create a single class that hosts all of the Attached Properties.

One of those properties will control whether the Effect is to be shown or not. The rest of the properties control visible portions of the Effect.

When the Effect should be shown – due to the propertyChanged delegate again – the delegate adds the effect to the Effects collection of the control.

Keeping track of adding and removing Effects via Attached Properties

Now – let’s say there are other properties that may want to be changed at runtime that are part of the Effect – Color, Size, etc … how would you implement that?

The Effect has the OnElementPropertyChanged function to override. That function gets fired every time a property on the target control get changed … even for Attached Properties!!

That means – using the Element property in the Effect, you can retrieve values out of the Attached Property (because the getter will be static and you will pass in the Element).

Using that value – you can update whatever property you need to in the platform implementation of the Effect! (Here’s an article explaining the whole process.)

Using the OnElementPropertyChanged function, the Effect can see what property was changed and then grab its value and update the visual.

Consuming such an Effect would look something like this:

<ContentView Margin="10" local:BorderEffects.HasBorder="true" local:BorderEffects.BorderColor="{StaticResource DividerColor}">

Then as a side note / mic drop … Attached Properties can also go into Styles. That means you can apply Effects to many controls at once! Sweet!

Summing It Up

Turns out I should have took the time to understand Attached Properties a long time ago. Not only do they do basic communication between elements – they also can help add commands to any event or even get many different properties of Effects to be updatable at runtime! Then there’s all sorts of use cases when creating custom layouts or implementing services that a visual element needs to consume. I’m thinking I’ll be using Attached Properties much more often now!

Attached Properties!!