1
我在WP应用程序中使用这样的枚举:如何将枚举绑定到WP中的listpicker?
公共枚举性别 { 男人= 0, 女人,其他 }
我如何编写代码,Listpicker项目是性别枚举项目。为了清楚地说明,我希望用户从Listpicker中选择性别。请帮忙。
我在WP应用程序中使用这样的枚举:如何将枚举绑定到WP中的listpicker?
公共枚举性别 { 男人= 0, 女人,其他 }
我如何编写代码,Listpicker项目是性别枚举项目。为了清楚地说明,我希望用户从Listpicker中选择性别。请帮忙。
我假设你想绑定到枚举类型的属性,像这样?
public enum EnumType { Item1, Item2 }
public EnumType Property { get; set; }
这是我做的:
(构造函数)
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}
(在您的命名空间的地方)
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);
}
}
在我的情况,我也想用的,而不是他们的名字枚举的说明,所以我用这个代码,而不是“在构造”上面的一行:
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;
Enum.GetValues在WP7中不可用 – Soonts 2013-10-13 23:45:27
您是否尝试过做像这样? http://stackoverflow.com/questions/3935953/how-do-i-bind-an-enum-to-my-listbox – 2012-02-23 10:59:42
没有,但我现在想,多亏 – 2012-02-23 11:03:02
这是非常有帮助,谢谢。但我现在有其他问题。 如果Listpicker项目数量是3(或更少3),当前页面中的pistpicker以combobox的形式打开,但超过3则打开其他页面。不像组合框。我如何解决这个问题? – 2012-02-23 11:34:57