
Attached Properties in Code
Attached properties do not have the typical CLR "wrapper" methods for easy get/set access like other dependency properties do. This is because the attached property is not necessarily part of the CLR namespace for instances where the property is set (although it could be, that is not forbidden). A XAML processor must be able to set those values when XAML is parsed into an object tree. The owner type of the attached property must implement dedicated accessor methods in the form GetPropertyName and SetPropertyName. These dedicated accessor methods are also how you must get or set the attached property in code. From a code perspective, an attached property is similar to a backing field that has method accessors instead of property accessors, and that backing field can exist on any object rather than needing to be specifically defined.
The following example shows how you can set an attached property in code. In this example, myCheckBox is an instance of the CheckBox class.
Canvas myC = new Canvas();
CheckBox myCheckBox = new CheckBox();
myCheckBox.Content = "Hello";
myC.Children.Add(myCheckBox);
Canvas.SetTop(myCheckBox, 75);
Similar to the XAML setting example, if myCheckBox had not already been added as a child element of myC by the third line of code, the fourth line of code would not raise an exception, but the property value would not interact with a Canvas parent and thus would do nothing. Only a Canvas..::.Top value set on a child element combined with the presence of a Canvas parent element will cause an effective behavior in the rendered application.