Pages

Friday, December 27, 2013

Binding enum to WPF combobox

Many times I found myself binding combobox to a set of values. A common scenario is that those values are just strings - representation of a application state, so creation of a static collection of strings was not very attractive for me. Enums are naturally fit in this scenario. But how to bind combobox to the enum? To comfortably bind enum its items should have descriptions - they will be used as a values for combobox. But here is a small helper to do this:
public static class EnumHelper
{
  public static string Description(this Enum eValue)
  {
    var nAttributes = eValue.GetType().GetField(eValue.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);

    if (!nAttributes.Any())
      return eValue.ToString();

    var descriptionAttribute = nAttributes.First() as DescriptionAttribute;
    if (descriptionAttribute != null)
      return descriptionAttribute.Description;

    return eValue.ToString();
  }

  public static IEnumerable<KeyValuePair<Enum, string>> GetAllValuesAndDescriptions<TEnum>() where TEnum : struct, IConvertible, IComparable, IFormattable
  {
    if (!typeof(TEnum).IsEnum)
      throw new ArgumentException("TEnum must be an Enumeration type");

    return from e in Enum.GetValues(typeof(TEnum)).Cast<Enum>()
           select new KeyValuePair<Enum, string>(e, e.Description());
  }
}


public enum WorkModes
{
  [Description("Simple mode")]
  Simple,
  [Description("Complex mode")]
  Complex,
  [Description("Third (optional) option")]
  Etc
}

//from windows loaded event - bind itemsSource of combobox to enum.
//and set it to default value
private void Window_Loaded(object sender, RoutedEventArgs e)
{
  cbCurrentState.ItemsSource = EnumHelper.GetAllValuesAndDescriptions();
  cbCurrentState.SelectedIndex = 0;
}

//And combo box declaration:

No comments:

Post a Comment