开发者

What are the various uses of Attached Properties?

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 r开发者_开发技巧eally helpful!)


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.


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):


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


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.


Attaching an ICommand to ANY event: http://geekswithblogs.net/HouseOfBilz/archive/2009/08/27/adventures-in-mvvm-ndash-binding-commands-to-any-event.aspx

Great for those of us using MVVM.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜