Pages

Wednesday, 8 May 2013

Difference between Dependency Property and Attached Property in WPF


Difference between Dependency Property and Attached Property in WPF

Attached properties are a type of dependency property. But there is a minor difference between dependency property and attached property in WPF. Lets try to understand them.

1. Concept and Usage of Attached Property and Dependency Property

Attached properties allows container to create a property which can be used by any child UI elements whereas dependency property is associated with that particular elements and can help in notification of changes and reacting to that changes.

Attached properties are basically meant for the container elements.like if you have a grid and you have grid.row, now this is considered to be an attached property of a grid element. Also you can use this property in texbox, button etc to set its place in the grid.

Attached properties are used a lot for layout-related information. For example, Canvas needs Left/Top coordinates, Grid needs a Row and a Column, DockPanel needs a Dock information etc. It would be a mess if all of this had to be declared on every control that can be layouted. So they are declared on the corresponding panel, but used on any control.

2. Implementation of Attached Property and Dependency Property

Attached properties and normal dependency properties include the methods used to register them with the DependencyObject. 

For attached properties, DependencyProperty.RegisterAttached and DependencyProperty.RegisterAttachedReadOnly are used and for dependency properties DependencyProperty.Register and DependencyProperty.RegisterReadOnly are used.

The difference between DependencyProperty.Register() and DependencyProperty.RegisterAttached() is that .Register() is used to register a 'regular' dependency property on a DependencyObject, while .RegisterAttached() is used to set an 'attached' dependency property.

No comments:

Post a Comment