Wil
Wil

Reputation: 10604

Enum to Drop Down Box to method

Basically, what is the best way of doing this?

I have an Enum which has all the possible resolutions and I want them to be displayed on a drop down combobox.

So far, I found I could bind the enum to the combobox like:

comboBox2.DataSource = Enum.GetNames(typeof(Resolution));

However, in a method, I have:

public void testmethod(Resolution res){}

and I can't think of a way to convert back. I was thinking of changing the method to use a string, but then I will have to do a case or ifs in the method to convert back to the enum.

In addition, I ideally want some of the names to have spaces. I have read about the [Description("Description with spaces")] but I think this only gets applied on ToString.

Even if I was to do some sort of loop and add each item to the box via ToString, it will still return a string.

I am not really sure how to proceed other than to dump the Enum all together and just go for a different approach.

I was just wondering in a similar situation, what would you do?

Upvotes: 2

Views: 1412

Answers (6)

weston
weston

Reputation: 54791

Populate an Observable Collection to bind to.

public class MyVM : BindableObject //where BindableObject is a base object that supports INotifyPropertyChanged and provides a RaisePropertyChanged method
{
    private readonly ObservableCollection<MyEnum> _myEnums;
    private MyEnum _selectedEnum;

    public MyVM()
    {
       //create and populate collection
       _myEnums = new ObservableCollection<MyEnum>();
       foreach (MyEnum myEnum in Enum.GetValues(typeof(MyEnum)))
       {
         _myEnums.Add(myEnum);
       }
     }

     //list property to bind to
     public IEnumerable<MyEnum> MyEnumValues
     {
         get { return _myEnums; }
     }

     //a property to bind the selected item to
     public MyEnum SelectedEnum
     {
         get { return __selectedEnum; }
         set
         {
            if (!Equals(__selectedEnum, value))
            {
              __selectedEnum = value;
              RaisePropertyChanged("SelectedEnum");
            }
         }
     }
}

Then in xaml to bind:

<ComboBox ItemsSource="{Binding Path=MyEnumValues}"
          SelectedItem="{Binding Path=SelectedEnum}"/>

Note that technically as the list is not changing at runtime, we do not need ObservableCollection a List would do, but I think ObservableCollection is a good habit to get into when working with VMs.

Upvotes: 0

code4life
code4life

Reputation: 15794

Can't you just do a Enum.Parse(typeof(Resolution), comboBox2.SelectedText)?

So your call to testmethod would look like:

testmethod((Resolution)Enum.Parse(typeof(Resolution), comboBox2.SelectedText));

Assuming that the combo box's DropDownStyle is set to DropDownList.

Upvotes: 1

Femaref
Femaref

Reputation: 61437

You can use the Enum.Parse(Type t, string s) method to get an enum from a string, in your case it would be:

Resolution r = (Resolution)Enum.Parse(typeof(Resolution), input);

Concerning your description idea, I use the following in my code:

public static class EnumExtender
{
    public static string StringValue(this Enum value)
    {
        FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
        EnumStringValueAttribute[] attributes = (EnumStringValueAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumStringValueAttribute), false);


        if (attributes.Length > 0)
        {
            return attributes[0].Value;
        }


        return value.ToString();
    } 
}

public class EnumStringValueAttribute : Attribute
{
    public string Value { get; set; }


    public EnumStringValueAttribute(string value) : base()
    {
        this.Value = value;
    }
}

Of course, you'll have to remember to use the extension method to get the description - converting it back is something different however.

Upvotes: 0

Shadow Wizard
Shadow Wizard

Reputation: 66388

I would go with some sort of map - each enumeration value will have its own string description.

Code for this can be:

public enum Resolution
{
   High,
   Medium,
   Low
}

Dictionary<Resolution, string> Descriptions = new Dictionary<Resolution, string>();
Descriptions.Add(Resolution.High, "1920x1080");
Descriptions.Add(Resolution.Medium, "1280x720");
Descriptions.Add(Resolution.Low, "800x600");

comboBox2.DataSource = Descriptions.Values;

public void testmethod(Resolution res)
{
   string description = Descriptions[res];
   ...
}

public void testmethod2(string description)
{
   Resolution res = Descriptions.Keys.ToList().Find(k => Descriptions[k].Equals(description));
   ...
}

Upvotes: 1

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158309

You can use Enum.TryParse<TEnum>:

Resolution res;
if (Enum.TryParse<Resolution>(input, out res))
{
    // use res
}
else
{
   // input was not a valid Resolution value
}

Upvotes: 0

msarchet
msarchet

Reputation: 15242

I would use a LookupEdit instead, and tie the Enum Value to the Key and the Enum.GetNames(typeof(Resolutions)); to the displayed value on the edit. Then when the user selects an item you get the actual value instead of the name.

Upvotes: 1

Related Questions