Attached Properties – What Are They Good For?

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 …

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

Parameter Description
string propertyName The name of the attached property
Type returnType The data type the attached property will be returning
Type declaringType The class declaring the bindable property
Object defaultValue The value of the property should nothing be assigned to it
BindingPropertyChangedDelegate propertyChanged A 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:

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.

Then to consume it:

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:

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!!

Matthew Soucoup on EmailMatthew Soucoup on GithubMatthew Soucoup on LinkedinMatthew Soucoup on Twitter
Matthew Soucoup
Matthew Soucoup
Matthew is a Xamarin MVP and Certified Xamarin Developer from Madison, WI. He started Code Mill Technologies and is the founder of the Madison Mobile .Net Developer's Group. 

Matt regularly speaks on .Net and Xamarin development at user groups, code camps and conferences throughout the nation, including Xamarin Evolve, That Conference, Prairie.Code(), MKEdotNET, St. Louis Days of .Net, and CodeMash.

When he's not developing cross platform apps, writing blog posts, or creating the next great talk, Matt enjoys brewing beer with jalapeños from his garden and playing 80s tunes on the piano.
  • Ciro

    Hi, Matthew! Thank you for share this tip.
    It’s help me a lot!

    Regards,

    Ciro.

    • You’re most welcome Ciro – thank you for the kind words!!

  • Dave Parker

    Hi Matthew, great post! one thing, do you have an example of what you mean by this: “Attached Properties can also go into Styles. That means you can apply Effects to many controls at once! Sweet!”

    it sounds awesome and I would love to see how it works.

    • Thanks Dave! I’ll get a working example together in the next couple of days and put it on GitHub – I’ll update the post (and reply to this comment) when I get it done.

    • Brad

      At the simpliest, this can turn:

      into

      [hope that posts well-formatted]

      • Hey Brad – that didn’t come through at all … if you could put it into a Gist – I could try to get it added….

    • Hi Dave,

      I have a demo solution up on GitHub here: https://github.com/codemillmatt/attached-properties. It’s a simple shadow effect (iOS only on a UILabel). In the core project, look in the Effects directory – ShadowAttachedProperties static class. That will add or remove the effect from the X.F. Label every time an attached HasShadow property changes.

      Then in the iOS project, take a look at the LabelShadowEffect class, in particular the OnElementPropertyChanged. It’s in here that the Effect can look to see when attached properties change.

      Then back in the core project – LabelShadowPage.xaml has the effect being added via a style to one Label (but not another).

      Hope that helps!

%d bloggers like this: