我不知道多少,這會有所幫助,但我用枚舉的擴展方法,看起來像這樣:
/// <summary>
/// Returns the value of the description attribute attached to an enum value.
/// </summary>
/// <param name="en"></param>
/// <returns>The text from the System.ComponentModel.DescriptionAttribute associated with the enumeration value.</returns>
/// <remarks>
/// To use this, create an enum and mark its members with a [Description("My Descr")] attribute.
/// Then when you call this extension method, you will receive "My Descr".
/// </remarks>
/// <example><code>
/// enum MyEnum {
/// [Description("Some Descriptive Text")]
/// EnumVal1,
///
/// [Description("Some More Descriptive Text")]
/// EnumVal2
/// }
///
/// static void Main(string[] args) {
/// Console.PrintLine(MyEnum.EnumVal1.GetDescription());
/// }
/// </code>
///
/// This will result in the output "Some Descriptive Text".
/// </example>
public static string GetDescription(this Enum en)
{
var type = en.GetType();
var memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
return en.ToString();
}
您可以使用自定義屬性的getter你的對象返回名稱:
public class TestResult
{
public string TestDescription { get; set; }
public ExpectationResult RequiredExpectationResult { get; set; }
public ExpectationResult NonRequiredExpectationResult { get; set; }
/* *** added these new property getters *** */
public string RequiredExpectationResultDescr { get { return this.RequiredExpectationResult.GetDescription(); } }
public string NonRequiredExpectationResultDescr { get { return this.NonRequiredExpectationResult.GetDescription(); } }
}
然後網格綁定到 「RequiredExpectationResultDescr」 和 「NonRequiredExpectationResultDescr」 屬性。
這可能有點過於複雜,但它的我想出了:)
謝謝馬克!與我們的EnumHelper(類似於rally25rs的答案的第一部分)相結合,這個優雅的解決方案可以很好地工作 - 在DataGridView中。不幸的是我發現DevExpress.XtraGrid.GridControl不**檢測TypeConverter屬性。嘆。但你的回答顯然是正確的。 – TrueWill 2009-10-08 21:15:36
...你指出我在正確的方向。我發現Developer Express並不打算支持這一點,並提供了這種解決方法:http://www.devexpress.com/Support/Center/p/CS2436.aspx – TrueWill 2009-10-08 21:21:16