Cảm ơn tất cả các bạn cho tất cả các câu trả lời. Cuối cùng tôi đã sử dụng kết hợp từ Rex M và adrianbanks, và thêm các cải tiến của riêng tôi, để đơn giản hóa việc liên kết với ComboBox.
Các thay đổi là cần thiết vì, trong khi làm việc trên mã, tôi nhận ra đôi khi tôi cần để có thể loại trừ một mục liệt kê khỏi kết hợp. Ví dụ:
Enum Complexity
{
// this will be used in filters,
// but not in module where I have to assign Complexity to a field
AllComplexities,
NotSoComplex,
LittleComplex,
Complex,
VeryComplex
}
Vì vậy, đôi khi tôi muốn picklist để hiển thị tất cả nhưng AllComplexities (trong add - chỉnh sửa module) và thời gian khác để hiển thị tất cả (trong các bộ lọc)
Dưới đây là những gì tôi đã làm:
- Tôi đã tạo phương thức tiện ích mở rộng, sử dụng Thuộc tính mô tả làm khóa tìm kiếm bản địa hóa. Nếu thuộc tính Mô tả bị thiếu, tôi tạo khoá địa phương tra cứu là EnumName_ EnumValue. Cuối cùng, nếu bản dịch bị thiếu, tôi chỉ tách tên enum dựa trên camelcase để tách các từ như được hiển thị bởi adrianbanks. BTW, TranslationHelper là một trình bao bọc xung quanh resourceMgr.GetString (...)
Mã đầy đủ được hiển thị bên dưới
public static string GetDescription(this System.Enum value)
{
string enumID = string.Empty;
string enumDesc = string.Empty;
try
{
// try to lookup Description attribute
FieldInfo field = value.GetType().GetField(value.ToString());
object[] attribs = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (attribs.Length > 0)
{
enumID = ((DescriptionAttribute)attribs[0]).Description;
enumDesc = TranslationHelper.GetTranslation(enumID);
}
if (string.IsNullOrEmpty(enumID) || TranslationHelper.IsTranslationMissing(enumDesc))
{
// try to lookup translation from EnumName_EnumValue
string[] enumName = value.GetType().ToString().Split('.');
enumID = string.Format("{0}_{1}", enumName[enumName.Length - 1], value.ToString());
enumDesc = TranslationHelper.GetTranslation(enumID);
if (TranslationHelper.IsTranslationMissing(enumDesc))
enumDesc = string.Empty;
}
// try to format CamelCase to proper names
if (string.IsNullOrEmpty(enumDesc))
{
Regex capitalLetterMatch = new Regex("\\B[A-Z]", RegexOptions.Compiled);
enumDesc = capitalLetterMatch.Replace(value.ToString(), " $&");
}
}
catch (Exception)
{
// if any error, fallback to string value
enumDesc = value.ToString();
}
return enumDesc;
}
Tôi tạo ra một lớp helper generic dựa trên Enum, cho phép để ràng buộc các enum dễ dàng để DataSource
public class LocalizableEnum
{
/// <summary>
/// Column names exposed by LocalizableEnum
/// </summary>
public class ColumnNames
{
public const string ID = "EnumValue";
public const string EntityValue = "EnumDescription";
}
}
public class LocalizableEnum<T>
{
private T m_ItemVal;
private string m_ItemDesc;
public LocalizableEnum(T id)
{
System.Enum idEnum = id as System.Enum;
if (idEnum == null)
throw new ArgumentException(string.Format("Type {0} is not enum", id.ToString()));
else
{
m_ItemVal = id;
m_ItemDesc = idEnum.GetDescription();
}
}
public override string ToString()
{
return m_ItemDesc;
}
public T EnumValue
{
get { return m_ID; }
}
public string EnumDescription
{
get { return ToString(); }
}
}
Sau đó, tôi đã tạo ra một phương pháp tĩnh chung trả về Danh sách>, như bên dưới
public static List<LocalizableEnum<T>> GetEnumList<T>(object excludeMember)
{
List<LocalizableEnum<T>> list =null;
Array listVal = System.Enum.GetValues(typeof(T));
if (listVal.Length>0)
{
string excludedValStr = string.Empty;
if (excludeMember != null)
excludedValStr = ((T)excludeMember).ToString();
list = new List<LocalizableEnum<T>>();
for (int i = 0; i < listVal.Length; i++)
{
T currentVal = (T)listVal.GetValue(i);
if (excludedValStr != currentVal.ToString())
{
System.Enum enumVal = currentVal as System.Enum;
LocalizableEnum<T> enumMember = new LocalizableEnum<T>(currentVal);
list.Add(enumMember);
}
}
}
return list;
}
và một wrapper để trở lại danh sách với tất cả các thành viên
public static List<LocalizableEnum<T>> GetEnumList<T>()
{
return GetEnumList<T>(null);
}
Bây giờ chúng ta hãy đặt tất cả mọi thứ lại với nhau và liên kết với kết hợp thực tế:
// in module where we want to show items with all complexities
// or just filter on one complexity
comboComplexity.DisplayMember = LocalizableEnum.ColumnNames.EnumValue;
comboComplexity.ValueMember = LocalizableEnum.ColumnNames.EnumDescription;
comboComplexity.DataSource = EnumHelper.GetEnumList<Complexity>();
comboComplexity.SelectedValue = Complexity.AllComplexities;
// ....
// and here in edit module where we don't want to see "All Complexities"
comboComplexity.DisplayMember = LocalizableEnum.ColumnNames.EnumValue;
comboComplexity.ValueMember = LocalizableEnum.ColumnNames.EnumDescription;
comboComplexity.DataSource = EnumHelper.GetEnumList<Complexity>(Complexity.AllComplexities);
comboComplexity.SelectedValue = Complexity.VeryComplex; // set default value
Để đọc chọn giá trị và sử dụng nó, tôi sử dụng mã như bên dưới
Complexity selComplexity = (Complexity)comboComplexity.SelectedValue;
Xem –