Extending a solution for simple binding to a 'Text property to multiple Controls to handle binding to any Type?

一世执手 提交于 2019-11-29 15:32:07

It really depends what you want to do; but ultimately common data-binding (for simple properties, done manually) consists of:

  • obtaining a property; preferably via TypeDescriptor.GetProperties(obj)[propName], giving you an abstraction (PropertyDescriptor)
  • asking the property if it is read-only (.IsReadOnly)
  • obtain (or set) the value (.GetValue(), .SetValue())
  • asking it for a converter to format / parse the value (.Converter, .ConvertFromString(), .ConvertToString()) THIS is a key bit that means you don't have to worry about what the data type is
  • asking it for the caption (.DisplayName, or .Name if that it empty/null)
  • asking it if it supports property-specific notification (.SupportsChangeEvents)
  • asking it to add/remove a change handler (.AddValueChanged(), .RemoveValueChanged())
  • you might also want to look at whether the object supports centralised notification (look for INotifyPropertyChanged)

If you might be binding to a list rather than a single object: - the list might be abstracted behind IListSource - the list might have custom properties, so check for ITypedList - otherwise, identify the Type of the items and use TypeDescriptor.GetProperties(type) - you need to consider a "currency manager" (i.e. should all the things bound to the same list be pointing to the same record in the list all the time)

There are also things like ICustomTypeDescriptor and TypeDescriptionProvider to consider, but most of the time TypeDescriptor handles this for you automatically.

As you can see - lots of things to think about! Lots of work... the one thing that you don't have to do is reflection; this is abstracted behind PropertyDescriptor. The reason for this is that not all data is static-typed; think about DataTable - the columns (which map to bindable data properties) are not fixed at compile-time, so reflection isn't appropriate. Likewise, some other types have custom "property bag" implementations. PropertyDescriptor lets your code handle either dynamic (not in the 4.0 sense) and reflective properties identically. It also works nicely with things like "HyperDescriptor", another property customisation.

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