编辑:更好的解决方案
正如安德斯评论的那样,Enum.GetValues()
可能是一个更好的主意。绑定的问题之一enums是标识符不能包含空格,所以默认情况下,绑定不会给你一个很好的可读字符串。
但是,您可以用Display
属性。参考System.ComponentModel.DataAnnotations.
public class Equipment
{
public enum Type
{
Detector,
[Display(Name="Vegetation Clearance")]
VegetationClearance,
Removal,
Engaging
}
}
现在将以下属性添加到您的 ViewModel 中:
public IEnumerable<Equipment.Type> EquipmentTypes
{
get { return Enum.GetValues(typeof(Equipment.Type)).Cast<Equipment.Type>(); }
}
private Equipment.Type _selectedType;
public Equipment.Type SelectedType
{
get { return _selectedType; }
set { _selectedType = value; RaisePropertyChanged(() => SelectedType); }
}
我们要做的是创建一个值转换器转换一个enum到一个用于显示的字符串中,该字符串将返回显示名称属性(如果存在)。
public class EnumDisplayNameValueConverter : MvxValueConverter
{
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return GetEnumDisplayName((Enum)value);
}
public static string GetEnumDisplayName(Enum value)
{
var t = value.GetType();
var ti = t.GetTypeInfo();
var fi = ti.DeclaredFields.FirstOrDefault(x => x.Name == value.ToString());
var attributes = (DisplayAttribute[])fi.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes != null && attributes.Length > 0)
{
return attributes[0].Name;
}
return value.ToString();
}
}
为了使用值转换器,您需要在微调器中指定项目模板和下拉模板:
<Mvx.MvxSpinner
android:id="@+id/type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
local:MvxItemTemplate="@layout/spinneritem"
local:MvxDropDownItemTemplate="@layout/spinnerdropdownitem"
local:MvxBind="ItemsSource EquipmentTypes; SelectedItem SelectedType" />
并创建 spinneritem/spinnerdropdownitem 布局:
<?xml version="1.0" encoding="utf-8" ?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
local:MvxBind="Text EnumDisplayName(.)" />
请注意,我们绑定到EnumDisplayName(.)
。这就是值转换器和.
表示当前值enum.
我在 GitHub 上添加了一个示例。https://github.com/kiliman/MvxSpinnerEnumSample https://github.com/kiliman/MvxSpinnerEnumSample