簡體   English   中英

如何在Winforms中將枚舉轉換為bool for DataBinding?

[英]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.TypeSecure ,我希望通過數據綁定來檢查SecureCheckbox

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();
 }

以下是一些附加這些事件處理程序的代碼:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM