hattenn
hattenn

Reputation: 4399

How does setting an attached property programmatically work?

I'm reading about attached properties and I've just read that they can be set with something similar to the following:

Grid.SetRow(myElement, 0);

If this is a static method, how does Grid.SetRow() now which Grid it should put myElement into? Or does it work in a way that it somehow associates myElement with row 0, so when there's a new Grid object including myElement, it can just check in what row myElement should go to?

Upvotes: 2

Views: 166

Answers (2)

poke
poke

Reputation: 387607

When setting attached properties, the value is stored in the element only, not the type the attached property belongs to.

For example, the attached row property is implemented like this:

public static readonly DependencyProperty RowProperty = ...;

public static void SetRow(UIElement element, int value)
{
    element.SetValue(RowProperty, value);
}

public static int GetRow(UIElement element)
{
    return (int)element.GetValue(RowProperty);
}

So when you call Grid.SetRow, then internally element.SetValue is called. As element is a dependency object, it can store those additional properties. You can imagine it as Dictionary<DependencyProperty, object> inside the dependency object (albeit it’s a lot more complex in fact) which you can access using SetValue and GetValue.

So the value is only stored inside of the dependency object itself. Now, when the Grid renders itself, it will iterate through its children to call its measurement and layout routines. It will also call Grid.GetRow for each of those children to see if the attached row property was set, and respect those choices during its own layout phase accordingly.

Upvotes: 3

Thomas Levesque
Thomas Levesque

Reputation: 292415

If this is a static method, how does Grid.SetRow() now which Grid it should put myElement into?

It doesn't know

Or does it work in a way that it somehow associates myElement with row 0, so when there's a new Grid object including myElement, it can just check in what row myElement should go to?

Yes, exactly

Upvotes: 1

Related Questions