What are the various uses of Attached Properties?

最后都变了- 提交于 2020-01-13 13:09:12

问题


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:


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.




回答2:


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




回答3:


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




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/3195638/what-are-the-various-uses-of-attached-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!