Creating Attached Properties

Attached Properties are a special kind of dependency properties. They are most likely used to specify some layout information that is containing information for the containing control, not the control that on which we set it. To demonstrate the usage of the attached properties, we are going to implement a simple layout control which has the capability of putting elements on the left and right, or if the side is not set below the left and right stacks. The completed solution for this article can be found in the Z11_AttachedProperties directory of my WpfWednesday git repository.

We first start by creating a StackPanel derived class, which has the following members:

  • _grid, for placing the left and right control stacks on the top of the inherited StackPanel,
  • _left, for placing the controls on the left and,
  • _right, for placing the controls on the right.

In the constructor, we also place these members correctly. The resulting class will be the one below:

The next step is to define the possible values for the attached property. To do this, we declare the Side enumeration:

After having the value, we must register the property itself and two helper static methods, so that the WPF system is able to use our property. The property registration is basically the same as how we did during a simple dependency property in the article titled Dependency Properties, except that we should use the RegisterAttached static method of the DependencyProperty class. The Get and Set methods are similar as for the simple dependency properties, just this time they are not going to be property getters and setters but static methods. Pay attention to the names of them, they must be the in the scheme of GetPropertyName and SetPropertyName.

Now comes the tricky part. Whenever the position changes, we must detach the object from its actual logical parent, and then reattach it as a child of the correct StackPanel.

The only remaining code to write is to try it out, here is the appropriate code block from the MainWindow:

For more information on attached dependency properties, you can visit the Attached Properties Overview MSDN site.

I hope you enjoyed playing with the attached dependency properties.

You can connect with me on LinkedIn, Twitter or you can register on the blog. Share if you found this article useful or know somebody who would benefit from reading it.

By subscribing to the email list, you will be notified about new posts.


No comments yet.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Powered by WordPress. Designed by WooThemes