I have the following code to load an enumeration into a bound combo box, but am not quite happy with it.
I would prefer to store the actual enum
value in the combo box and bind directly to it.
However, I can't quite figure out how to do so.
public enum HemEnum
{
HemNone = -1,
Hemsew = 0,
HemWeld = 1,
Hemdoublefold = 2
}
public static void LoadHemCombo(ComboBox cbo)
{
var values = from Enum e in Enum.GetValues(typeof(HemEnum))
select new { ID = e, Name = e.ToString() };
foreach (var value in values)
{
var s = GetHemTypeDescription((HemEnum)value.ID );
cbo.Items.Add(s);
}
}
public static string GetHemTypeDescription(HemEnum hemType)
{
string s = null;
switch (hemType)
{
case HemEnum.HemNone:
s = "none";
break;
case HemEnum.Hemsew:
s = "sewn";
break;
case HemEnum.HemWeld:
s = "welded";
break;
case HemEnum.hemdoublefold:
s = "double folded";
break;
default:
s = "not known";
break;
}
return s;
}
Inside the form load event I load the combo and bind to it.
LoadHemCombo(cboHem)
cboHem.DataBindings.Add("Text", myBindingSource, "HemTypeDescription");
class myObject
{
public string HemTypeDescription
{
get
{
return GetHemTypeDescription(this.HemType);
}
set
{
this.HemType = GetHemTypeFromDescription(value);
}
}
public static vHemEnum GetHemTypeFromDescription(string description)
{
int r =0;
for (var i = (int)HemEnum.HemNone; i <= (int)HemEnum.Hemdoublefold; i++)
{
var s = GetHemTypeDescription((HemEnum)i);
if (description == s)
{
r = i;
break;
}
}
return (HemEnum)r;
}
}
in the designer I set
myBindingSource.DataSource = myObject
and before loading the form I create an instance of myObject
and add it to myBindingSource
using
myBindingSource.Add(myObject)
ObjectDataProvider
to get all enum values in XAML and then bind it toItemsSource
. Here is a full example. \$\endgroup\$