Interacting with attached properties

The attached properties are a special kind of properties. They are defined on one control but actually affect another control. While this might sound a bit confusing, the truth is we have actually used attached properties all along without knowing what they really are. The attached properties can be recognized quite easily as they have a constant syntax of PropertyTypeName.AttachedPropertyName. Think about the Grid.Row property for example, or Grid.Column. In these cases, Grid is the type and the property we are setting for it is either Row or Column. The element, which we define this property on, TextBox, or any other UI Element, doesn't have a Grid.Row property. In fact, it doesn't even know if it's placed inside Grid, Canvas, StackPanel, or any other layout control. Instead, the Grid.Row property tells the parent Grid element in which row to place the calling object. If we take TextBox, which resides inside Grid, and set its Grid.Row property to 3, the element will be placed on the 4th grid row. (Remember, the row collection starts at 0!)

The attached properties aren't limited to the Grid element. Examine the following line of code:

<Rectangle Fill="#FF14F12C" Height="76" Canvas.Left="25" Canvas.Top="29" Width="196" RadiusX="5" RadiusY="5"/>

Can you recognize the attached properties on the preceding code? (Hint: remember the syntax!).

While the attached properties are mostly used in XAML, you can set and get their value in the code behind as well. Consider the following code snippet:

TextBox tb = new TextBox();
LayoutRoot.Children.Add(tb);
Grid.SetRow(tb, 2);

We are creating a new TextBox control in code, adding it to the LayoutRoot Grid control, and finally setting the row property of Grid on TextBox using the SetRow method of Grid.

The preceding code is equivalent to the following XAML code:

<TextBox Grid.Row="2"/>

Reading the row property back in the code behind is just as easy:

Grid.GetRow(tb);

We are using the GetRow method of Grid with the instance name of the control, which we wish to read the property from.

The concept of attached properties may be a bit odd at first, but it really becomes like second nature, the more you use it.

I strongly encourage you to read more on the subject of attached properties, in particular, how to create them on the MSDN website located at the following URL: http://msdn.microsoft.com/en-us/library/cc903943(v=vs.95).aspx.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.235.8