views:

67

answers:

5

I've seen some really varying uses of AttachedProperties so far in my adventures in WPF, and am wondering, what are some of the various uses?

I've seen fairly mundane uses, such as those found in Grid and Canvas, as well as some really cool hacks allowing binding to collections without setters. What other applications have you found for AttachedProperties? (Code samples really helpful!)

+1  A: 

Take a look into attached behaviours.

http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx //not sure on the quality of this link. First one I came to after googling.

Attaching a behavior to an object simply means making the object do something that it would not do on its own

The possibilities are pretty limitless on what you can actually do through attached behaviours but it can often reduce the need to extend controls or add logic to a code behind.

James Hay
+1  A: 

Use a custom attached property when you want to add properties to an existing class: Before it became available in Silverlight 4, I created an attached property for a DataGrid that allowed a column to be specified with a * width to take up all available space):

Michael S. Scherotter
A: 

Attached behaviours are the most useful thing I've seen so far as James said. One I use regularly is for putting text into a textbox and then having it disappear when it gets focus.

A greyed out string containing example input works well for this. So for a 'Name' textbox you might have the string "Joe Bloggs".

Stimul8d
Nice, a 'watermarked' textbox - we use those often on web sites.
mattdekrey
A: 

Here are a few more advanced uses I've found for them:

  1. Tagging regions (Prism pattern)

http://csharperimage.jeremylikness.com/2010/03/mef-instead-of-prism-for-silverlight-3.html

  1. Providing custom exports of XAML assets using the Managed Extensibility Framework (MEF)

http://csharperimage.jeremylikness.com/2010/03/custom-export-providers-with-custom.html

(Ties into the bullet for #1)

  1. Validation (attach the validation behavior to the control)

  2. Localization (I've seen attached properties used to access the resources and provide the translated value)

  3. Obviously behaviors are another major one as well.

Jeremy Likness