如何将枚举转换为Winforms中DataBinding的bool? [英] How to convert enum to a bool for DataBinding in Winforms?
问题描述
是否可以这样做?我需要使用:
Is it possible to do this? I need to use:
this.ControlName.DataBindings.Add (...)
所以我无法定义逻辑,而不是将我的枚举值绑定到code> bool
。
so I can't define logic other than bind my enum
value to a bool
.
例如:
(DataClass) Data.Type (enum)
编辑:
我需要绑定 Data.Type
这是一个枚举到复选框的已检查
财产。所以如果 Data.Type
是 Secure
,我想要 SecureCheckbox
通过数据绑定进行检查。
I need to bind Data.Type
which is an enum to a checkbox's Checked
property. So if the Data.Type
is Secure
, I want the SecureCheckbox
to be checked, through data binding.
推荐答案
Winforms绑定生成两个重要且有用的事件:格式
和解析
。
Winforms binding generates two important and useful events: Format
and Parse
.
当将数据从源数据拉入到控件中时,格式事件触发,当将数据从控件拉回数据源时,Parse事件触发。
The format event fires when pulling data from a source into a control and the Parse event fires when pulling data from a control back into the data source.
如果您处理这些事件,您可以在绑定期间更改/重新输入值。
If you handle these events you can alter/retype the values going back and forth during binding.
例如,这里有一对这些事件的示例处理程序:
For example here are a couple of example handlers for these events:
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();
}
这里是附加这些事件处理程序的一些代码:
And here is some code attaching these event handlers:
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处理程序,像:
So in your case you can just create a SecEnum to Bool handler for the format event and within that do something like:
SecEnum se = Enum.Parse(typeof(SecEnum), cevent.Value.ToString());
cevent.Value = (bool)(se== SecEnum.Secure);
,然后在解析过程中相反。
and then reverse that during parse.
这篇关于如何将枚举转换为Winforms中DataBinding的bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!