1

I use so enum in WP application:

public enum gender { man = 0, woman, other }

how can i write code that Listpicker items are gender enum items. To tell clear, i want user to select gender from Listpicker. Please, help.

Ceyhun Rehimov
  • 111
  • 2
  • 11
  • 1
    Have you tried to do something like this? http://stackoverflow.com/questions/3935953/how-do-i-bind-an-enum-to-my-listbox – Rodrigo Vedovato Feb 23 '12 at 10:59
  • No, but now im trying, thanks – Ceyhun Rehimov Feb 23 '12 at 11:03
  • That was very helpful, thanks. but i have other problem now. If Listpicker items count is 3 (or less 3) pistpicker opens as combobox in current page, but is more than 3 it opens other page. not as combobox. how i solve this problem? – Ceyhun Rehimov Feb 23 '12 at 11:34
  • more than 3 items in the same page would overflow, and scrolling within the combo box is not an option. You could try creating a listpicker which always opens as a full screen page. – abhinav Feb 24 '12 at 05:41
  • @Ceyhun Rehimov: Set the ItemCountThreshHoldValue to your Listpicker – Shashi Feb 24 '12 at 05:42

1 Answers1

0

I assume you want to bind to a property of the enum type, like this?

public enum EnumType { Item1, Item2 }
public EnumType Property { get; set; }

This is how I did it:

(in the constructor)

theListPicker.ItemsSource = Enum.GetValues(typeof(EnumType));

(XAML)

<phone:PhoneApplicationPage
    ...
    x:Name="_this"/>
    ...
    <phone:PhoneApplicationPage.Resources>
        <local:EnumIntConverter x:Name="enumIntConverter"/>
    </phone:PhoneApplicationPage.Resources>
    ....
    <toolkit:ListPicker ...
        SelectedIndex="{Binding ElementName=_this, Path=Property, Converter={StaticResource enumIntConverter}, Mode=TwoWay}

(somewhere in your namespace)

public class EnumIntConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (int)(EnumType)value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Enum.GetValues(typeof(EnumType)).GetValue((int)value);
    }
}

In my case, I also wanted to use the enum's Descriptions instead of their names, so I'm using this code instead of the "in the constructor" one-liner above:

Array rawValues = Enum.GetValues(typeof(EnumType));
List<string> values = new List<string>();
foreach (EnumType e in rawValues)
    values.Add((typeof(EnumType).GetMember(e.ToString())[0].GetCustomAttributes(typeof(DescriptionAttribute), false)[0] as DescriptionAttribute).Description);
theListPicker.ItemsSource = values;
Lucas Werkmeister
  • 2,584
  • 1
  • 17
  • 31