如何使用objectdatasource将枚举绑定到winform组合框 [英] How to bind enum to winform combobox using objectdatasource

查看:29
本文介绍了如何使用objectdatasource将枚举绑定到winform组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用对象数据源将类绑定到 Windows 窗体:将简单属性绑定到文本框工作正常,但我也需要将枚举属性绑定到组合框,例如:

i'm binding a class to a windows form using the object data source: binding simple properties to textboxes works fine, but i need to bind enum properties to comboboxes too, such as:

    public enum MyEnum
    {
        Val1,
        Val2,
        Val3
    }
    private MyEnum enumVal;

    public MyEnum EnumVal
    {
        get { return enumVal; }
        set { enumVal = value; }
    }

如何使用绑定源完成此操作?我尝试了各种方法,但这些方法都不起作用.谢谢

How to accomplish this using a binding source? I've tried in various ways, but none of these works. Thanks

推荐答案

我就是这样做的,但也许有更好的方法:

I do it like this, but perhaps there exists a better way:

List<ListItem<MyEnum>> enumVals = new List<ListItem<MyEnum>>();

foreach( MyEnum m in Enum.GetValues (typeof(MyEnum) )
{
    enumVals.Add (new ListItem<MyEnum>(m, m.ToString());
}

myComboBox.DataSource = enumVals;
myComboBox.ValueMember = "Key";
myComboBox.DisplayMember = "Description";

请注意,ListItem 是我创建的自定义类,其中包含一个 Key 属性和一个 Description 属性.

Note that ListItem<T> is a custom class that I've created, which contains a Key property and a Description property.

为了使您的属性与组合框的选定值保持同步,您必须:- 向组合框添加数据绑定,以便组合框的 SelectedValue 绑定到您的属性- 确保包含该属性的类实现了 INotifyPropertyChanged,这样当您更改该属性时,组合框的选定值也会随之更改.

In order to keep your property synchronized with the selected value of the combobox, you will have to : - add a databinding to the combobox, so that the SelectedValue of the combobox is bound to your property - make sure that the class which contains the property, implements INotifyPropertyChanged, so that when you change the property, the selected value of the combobox is changed as well.

myComboBox.DataBindings.Add ("SelectedValue", theBindingSource, "YourPropertyName");

public class TheClass : INotifyPropertyChanged
{
   public event PropertyChangedEventHandler PropertyChanged;

   private MyEnum _myField;

   public MyEnum MyPropertyName
   {
      get { return _myField; }
      set 
      {
         if( _myField != value )
         {
             _myField = value;
             if( PropertyChanged != null )
                  PropertyChanged ("MyPropertyName");
         }
      }
   }
}

这篇关于如何使用objectdatasource将枚举绑定到winform组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆