views:

190

answers:

2

Hello, I'm attempting to have a combo-box display a pre-defined set of values - in this case an enum. For example :

public enum Protocol
{
    UDP = 0,
    TCP,
    RS232
}

However I seem to fail at getting it done. Is this possible at all? I've attempted to use databinding however Blend only found all classes from the namespace, not the enum (which is not an object obviously)

+1  A: 

Bind names below to your ComboBox:

var names = Enum.GetNames( typeof(Protocol) );
Winston Smith
Simple as that, who would have thought lol
Maciek
A: 

Don't know about WPF but in webforms (since I use MVP) I bind a List> to the ddl. To get the list here is some code

var pairs = new List<KeyValuePair<string, string>>();

            pairs.Add(new KeyValuePair<string, string>("Please Select", String.Empty));

            for (int i = 0; i < typeof(DepartmentEnum).GetFields().Length - 1; i++)
            {
                DepartmentEnum de = EnumExtensions.NumberToEnum<DepartmentEnum>(i);
                pairs.Add(new KeyValuePair<string, string>(de.ToDescription(), de.ToString()));
            }

            MyView.Departments = pairs;

It uses extension methods on the enum:

 public static class EnumExtensions
    {
        public static string ToDescription(this Enum en) 
        {
            Type type = en.GetType();

            MemberInfo[] memInfo = type.GetMember(en.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),false);

                if (attrs != null && attrs.Length > 0)

                    return ((DescriptionAttribute)attrs[0]).Description;
            }

            return en.ToString();
        }

        public static TEnum NumberToEnum<TEnum>(int number )
        {
            return (TEnum)Enum.ToObject(typeof(TEnum), number);
        }
    }
epitka
Why was this down-voted? I would really like to know.
epitka
The OP wanted to populate the combobox with the names defined in the enum. Your solution uses reflection to look for custom description attributes on the enum, and binds those instead. While it may be useful, it's not what the OP wanted.
Winston Smith
How you managed to extract that information from the question is beyond me. He says: "combo-box display a pre-defined set of values - in this case an enum". Nowhere does he specify that it has to be names only.
epitka
@epitka, no his question is clear. It mentions "databinding" in the context of WPF which is a rich topic itself. You can bind controls to data directly in the XAML without writing code. I think you interpreted the question very differently because you don't know WPF. No big deal, just a minor downvote.
Brian Ensink