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";
Note that ListItem<T>
is a custom class that I've created, which contains a Key property and a Description property.
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");
and
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");
}
}
}
}