二、Control/DataSource映射的表示:BindingMapping
不论是数据绑定实体=〉控件),还是数据捕捉控件=〉实体)的实现都建立在两种之间存在着某种约定的映射之上,这个映射是整个DataBinder的核心所在。在这里,我定义了如下一个BindingMapping类型表示这个映射关系。
- public class BindingMapping: ICloneable
- {
- public Type DataSourceType { get; private set; }
- public Control Control { get; set; }
- public string ControlValueProperty { get; set; }
- public string DataSourceProperty { get; set; }
- public bool AutomaticBind { get; set; }
- public bool AutomaticUpdate { get; set; }
- public string FormatString { get; set; }
- public Type ControlValuePropertyType
- {
- get { return PropertyAccessor.GetPropertyType(this.Control.GetType(), this.ControlValueProperty); }
- }
- public Type DataSourcePropertyType
- {
- get { return PropertyAccessor.GetPropertyType(this.DataSourceType, this.DataSourceProperty); }
- }
- public BindingMapping(Type dataSourceType, Control control, string controlValueProperty, string dataSourceProperty)
- {
- //...
- this.DataSourceType = dataSourceType;
- this.Control = control;
- this.ControlValueProperty = controlValueProperty;
- this.DataSourceProperty = dataSourceProperty;
- this.AutomaticBind = true;
- this.AutomaticUpdate = true;
- }
- object ICloneable.Clone()
- {
- return this.Clone();
- }
- public BindingMapping Clone()
- {
- var bindingMapping = new BindingMapping(this.DataSourceType, this.Control, this.ControlValueProperty, this.DataSourceProperty);
- bindingMapping.AutomaticBind = this.AutomaticBind;
- bindingMapping.AutomaticUpdate = this.AutomaticBind;
- return bindingMapping;
- }
- }
这里我主要介绍一下各个属性的含义:
DataSourceType:作为数据源实体的类型;
Control:需要绑定的控件;
ControlValueProperty:数据需要绑定到控件属性的名称,比如TextBox是Text属性,而RadioButtonList则是SelectedValue属性;
DataSourceProperty:实体类型中的数据属性名称
AutomaticBind:是否需要进行自动绑定,通过它阻止不必要的自动数据绑定行为。默认值为True,如果改成False,基于该条映射的绑定将被忽略;
AutomaticUpdate:是否需要进行自动更新到数据实体中,通过它阻止不必要的自动数据捕捉行为。默认值为True,如果改成False,基于该条映射的数据捕捉定将被忽略;
FormatString:格式化字符串;
ControlValuePropertyType:控件绑定属性的类型,比如TextBox的绑定属性为Text,那么ControlValuePropertyType为System.String;
DataSourcePropertyType:实体属性类型。
需要补充一点的是:ControlValuePropertyType和DataSourcePropertyType使用到了之前定义的用于操作操作属性的组件ProcessAccessor。BindingMapping采用了克隆模式。