Wednesday, December 20, 2006

WPF - How to Programmatically Work With Attached Properties

The purpose of this post is to explain how to programmatically manipulate attached properties. I recently learned about them from the XAML side, however, I began to question how to use them from actual code. I really like the fact that XAML essentially maps Objects-to-Elements and Object Properties-to-Element Attributes. Then I saw these attached properties and I had to do some investigating to figure out how to manipulate these types of values from code. It's actually pretty easy, but you have to do it once to know how to do it. So I thought I would share my new found knowledge. The code used in this posting is available here. For an overview of Attached Properties, go here.

As a proof-of-concept, I created an application that simply displays a ComboBox that displays the available columns. The user can select a column and press the "Update" button. When the "Update" button is selected, the ComboBox will move to the selected column. The application looks like the following (I know it's ugly, but I've also been playing with some of the LinearGradientBrush stuff).

The XAML code that is of interest looks like the following (please bear in mind this is just a snippet and not the whole thing):

The Attached Properties in the code snipped used above are Grid.Row and Grid.Column. These properties define where in the grid the ComboBox is displayed. In order to set the attached property from the code behind, I had to essentially use 1 (yes one) line of code in the Click event of the Button. That line of code looks like the following:
Grid.SetColumn(ColumnComboBox, selectedIndex);
selectedIndex is just an integer set from the selected value of the combo box.

The "magic" occurs because Attached Properties essentially call static methods of an object. The static method is always named in the same manner. It is defined as ObjectType.SetNameOfProperty. So from the example, the ObjectType is Grid and the NameOfProperty is Column. Pretty kewl.

No comments: