2010-01-11 42 views
2

可以做到這一點嗎?我需要使用:如何在Winforms中將枚舉轉換爲數據綁定的布爾值?

this.ControlName.DataBindings.Add (...) 

,所以我不能定義比我enum值綁定到bool其他邏輯。

例如:

(DataClass) Data.Type (enum) 

編輯:

我需要綁定Data.Type這是一個枚舉複選框的Checked財產。所以如果Data.TypeSecure,我想通過數據綁定來檢查SecureCheckbox

+1

也許你可能會更具體一點你想綁定什麼?複選框到一個int列?枚舉到位列? – 2010-01-11 18:59:58

+0

對不起,我現在添加更多細節。 – 2010-01-11 19:26:07

回答

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

,這裏是一些代碼粘貼這些事件處理程序:

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

然後在解析過程中反轉。

+0

'Type type = typeof(T);'也可以與泛型類型參數一起使用。 – 2013-10-25 14:36:56

1

那麼,如果你綁定到你的類,你可以總是有這樣的一個屬性:

public bool IsSecured 
{ 
    get 
    { 
     if (myEnum == SecEnum.Secured) 
     return true; 
     else 
     return false; 
    } 
} 

,如果需要的setter只是扭轉。

+3

return(myEnum == SecEnum.Secured); – SwDevMan81 2010-01-11 20:03:43

+0

謝謝我用INotifyPropertyChanged做了類似的工作,但沒有奏效。因爲我正在更改數據本身,所以IsProperty沒有發出信號。我試圖自己做,但也沒有幫助。 – 2010-01-11 20:09:14