我有一个包含以下内容的枚举(例如):
clmn=543,
tclk=432, ,
tolf=876,
frol=654
我必须按排序顺序将此枚举键绑定到 ListBox 控件的 ItemsSource 属性。枚举应该按值排序。
请帮忙
此代码获取 MyEnum 的值并对它们进行排序,希望对您有所帮助。
var values = typeof(MyEnum).GetEnumValues();
Array.Sort(values);
MemberInfo[] memberInfos = typeof(MyEnum)
.GetMembers(BindingFlags.Public | BindingFlags.Static);
mylistBox.ItemSource = memberInfos.Select(x => x.Name).ToArray();
'对枚举进行排序的代码:
public static SortedList<int, string> GetEnumDataSource<T>()
{
Type myEnumType = typeof(T);
SortedList<int, string> returnCollection = new SortedList<int, string>();
try
{
if (myEnumType.BaseType == typeof(Enum))
{
string[] enumNames = Enum.GetNames(myEnumType);
int enumLength = enumNames.Length - 1;
for (int i = 0; i <= enumLength; i++)
{
returnCollection.Add(Convert.ToInt32(Enum.Parse(myEnumType, enumNames[i])), enumNames[i]);
}
}
}
catch (Exception exception1)
{
return null;
}
return returnCollection;
}
'将枚举绑定到下拉列表框的代码:
public void BindBox()
{
SortedList<int, string> phoneTypes = null;
phoneTypes = GetEnumDataSource<PhoneNumberType>();
if ((phoneTypes != null)) {
dropdownctrl.DataSource = phoneTypes;
dropdownctrl.DataValueField = "Key";
dropdownctrl.DataTextField = "Value";
dropdownctrl.DataBind();
}
}