Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind an enum to my listbox?

I have a Silverlight (WP7) project and would like to bind an enum to a listbox. This is an enum with custom values, sitting in a class library. How do I do this?

like image 858
DenaliHardtail Avatar asked Oct 14 '10 17:10

DenaliHardtail


People also ask

How do I turn an enum into a list?

The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.

How do I assign an enum to a string?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

Can we create list of enums?

tl;dr. Can you make and edit a collection of objects from an enum? Yes. If you do not care about the order, use EnumSet , an implementation of Set .

Can we assign variable to enum?

A change in the default value of an enum member will automatically assign incremental values to the other members sequentially. You can even assign different values to each member. The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong.


1 Answers

In Silverlight(WP7), Enum.GetNames() method is not available. You can use the following

public class Enum<T>
{
    public static IEnumerable<string> GetNames()
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new ArgumentException("Type '" + type.Name + "' is not an enum");

        return (
          from field in type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
          where field.IsLiteral
          select field.Name).ToList<string>();
    }
}

The static method will returns enumerable string collection. You can bind that to a listbox's itemssource. Like

this.listBox1.ItemSource = Enum<Colors>.GetNames();
like image 125
Prince Ashitaka Avatar answered Oct 02 '22 19:10

Prince Ashitaka