gpt4 book ai didi

c# - 如何在 Winforms 中将枚举转换为 bool 值以进行数据绑定(bind)?

转载 作者:行者123 更新时间:2023-11-30 19:34:11 24 4
gpt4 key购买 nike

这有可能吗?我需要使用:

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

所以除了将我的 enum 值绑定(bind)到 bool 之外,我无法定义逻辑。

例如:

(DataClass) Data.Type (enum)

编辑:

我需要将枚举 Data.Type 绑定(bind)到复选框的 Checked 属性。因此,如果 Data.TypeSecure,我希望通过数据绑定(bind)检查 SecureCheckbox

最佳答案

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

格式事件在将数据从源拉入控件时触发,Parse 事件在将数据从控件拉回数据源时触发。

如果您处理这些事件,您可以在绑定(bind)期间来回更改/重新键入值。

例如,这里有几个处理这些事件的示例:

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

然后在解析期间反转它。

关于c# - 如何在 Winforms 中将枚举转换为 bool 值以进行数据绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2044067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com