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