[英]How to convert enum to a bool for DataBinding in Winforms?
是否有可能做到这一点? 我需要用:
this.ControlName.DataBindings.Add (...)
所以除了将我的enum
值绑定到bool
之外,我无法定义逻辑。
例如:
(DataClass) Data.Type (enum)
编辑:
我需要将Data.Type
绑定到复选框的Checked
属性。 因此,如果Data.Type
是Secure
,我希望通过数据绑定来检查SecureCheckbox
。
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 to Bool处理程序,并在其中执行以下操作:
SecEnum se = Enum.Parse(typeof(SecEnum), cevent.Value.ToString());
cevent.Value = (bool)(se== SecEnum.Secure);
然后在解析期间将其反转。
好吧,如果你绑定到你的班级,你总是可以像这样拥有一个属性:
public bool IsSecured
{
get
{
if (myEnum == SecEnum.Secured)
return true;
else
return false;
}
}
如果需要,只需反转安装者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.