Winforms绑定会生成两个重要且有用的事件:Format
和Parse
。
将数据从源数据拉入控件时触发format事件,并且在将数据从控件拉回到数据源时触发Parse事件。
如果处理这些事件,您可以在绑定过程中更改/重新键入来回的值。
例如,下面是这些事件的几个例子处理程序:
public static void StringValuetoEnum<T>(object sender, ConvertEventArgs cevent)
{
T type = default(T);
if (cevent.DesiredType != type.GetType()) return;
cevent.Value = Enum.Parse(type.GetType(), cevent.Value.ToString());
}
public static void EnumToStringValue<T>(object sender, ConvertEventArgs cevent)
{
//if (cevent.DesiredType != typeof(string)) return;
cevent.Value = ((int)cevent.Value).ToString();
}
,这里是一些代码粘贴这些事件处理程序:
List<NameValuePair> bts = EnumHelper.EnumToNameValuePairList<LegalEntityType>(true, null);
this.cboIncType.DataSource = bts;
this.cboIncType.DisplayMember = "Name";
this.cboIncType.ValueMember = "Value";
Binding a = new Binding("SelectedValue", this.ActiveCustomer.Classification.BusinessType, "LegalEntityType");
a.Format += new ConvertEventHandler(ControlValueFormatter.EnumToStringValue<LegalEntityType>);
a.Parse += new ConvertEventHandler(ControlValueFormatter.StringValuetoEnum<LegalEntityType>);
this.cboIncType.DataBindings.Add(a);
所以你的情况,你可以只创建一个SecEnum为格式事件的Bool处理程序,并在其中执行类似操作:
SecEnum se = Enum.Parse(typeof(SecEnum), cevent.Value.ToString());
cevent.Value = (bool)(se== SecEnum.Secure);
然后在解析过程中反转。
也许你可能会更具体一点你想绑定什么?复选框到一个int列?枚举到位列? – 2010-01-11 18:59:58
对不起,我现在添加更多细节。 – 2010-01-11 19:26:07