views:

1318

answers:

2

What's the difference between the two, when should RegisterAttached() be used instead of .Register()?

+3  A: 

Do you mean DependencyProperty.Register() and DependencyProperty.RegisterAttached(), by chance? MSDN doesn't list a DependencyProperty.Attach() or DependencyProperty.AttachRegistered().

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.

The difference between the two types of dependency properties is reasonably straightforward: regular dependency properties are set on a particular DependencyObject just like you would any other .NET property. Attached properties, on the other hand, are associated with a particular DependencyObject (e.g. Grid) but are set on a completely separate DependencyObject, often a child of the DependencyObject that defines the attached property (e.g. Grid.Row, an attached property, is set on the children of a parent Grid).

More details on attached properties are on MSDN.

Nicholas Armstrong
+8  A: 

I assume you meant DependencyProperty.Register and DependencyProperty.RegisterAttached.

DependencyProperty.Register is used to register normal DependencyProperty. You can see those as just regular properties, with the added twist that they can take part in WPF's DataBinding, animations etc. In fact, they are exposed as normal property (with the get and set accessors) on top of the untyped DependencyObject.SetValue / GetValue. You declare those as part of your type.

Attached properties on the other hand are different. They are meant as an extensibility system. If you have ever used Extenders in Windows Forms, they are kind of similar. You declare them as part of a type, to be used on another type.

They 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.

You can use the same thing to attach any information to a DependencyObject if you need to. It can come in handy to just declare a piece of information that you can set in xaml just to be used later in a style for an existing class for example.

So those two kind of DependencyProperty serve a very different purpose. Regular properties (registered through Register() ) are used just like normal properties as part of the interface of your type. Attached properties (registered through RegisterAttached() ) are used as an extensibility point on existing classes.

Hope that clarifies it a bit.

Denis Troller
So attach can be used to add properties to classes that you don't own? Is that the difference?
Vaccano