2010-01-11 43 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