如何在Winforms中将枚举转换为bool for DataBinding?

Joa*_*nge 2 .net c# data-binding winforms

是否有可能做到这一点?我需要用:

this.ControlName.DataBindings.Add (...)
Run Code Online (Sandbox Code Playgroud)

所以除了将我的enum值绑定到a 之外,我无法定义逻辑bool.

例如:

(DataClass) Data.Type (enum)
Run Code Online (Sandbox Code Playgroud)

编辑:

我需要绑定Data.Type哪个是复选框Checked属性的枚举.因此,如果Data.TypeSecure,我希望SecureCheckbox通过数据绑定进行检查.

ris*_*ism 8

Winforms绑定生成两个重要且有用的事件:FormatParse.

将数据从源引入控件时会触发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();
 }
Run Code Online (Sandbox Code Playgroud)

以下是一些附加这些事件处理程序的代码:

 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);
Run Code Online (Sandbox Code Playgroud)

因此,在您的情况下,您可以为格式事件创建一个SecEnum to Bool处理程序,并在其中执行以下操作:

 SecEnum se = Enum.Parse(typeof(SecEnum), cevent.Value.ToString());
 cevent.Value = (bool)(se== SecEnum.Secure);
Run Code Online (Sandbox Code Playgroud)

然后在解析期间将其反转.