这是一个类似于
How to bind a custom Enum description to a DataGrid的问题,但在我的情况下,我有多个属性.
@H_502_7@解决方法
public enum ExpectationResult { [Description("-")] NoExpectation,[Description("Passed")] Pass,[Description("Failed")] Fail } public class TestResult { public string TestDescription { get; set; } public ExpectationResult requiredExpectationResult { get; set; } public ExpectationResult NonrequiredExpectationResult { get; set; } }
我绑定一个BindingList< TestResult>到WinForms DataGridView(实际上是一个DevExpress.XtraGrid.GridControl,但一般的解决方案将更广泛地适用).我想要描述而不是枚举名称.我该如何做到这一点? (没有对类/枚举/属性的约束;我可以随意改变它们.)
TypeConverter通常会做这个工作;这里有一些适用于DataGridView的代码 – 只需添加代码来读取描述(通过反射等) – 我刚刚使用了一个字符串前缀来显示自定义代码的工作).
注意你可能也想覆盖ConvertFrom.可以在类型或属性级别指定转换器(如果您只希望它适用于某些属性),并且还可以在运行时应用枚举不受您的控制.
using System.ComponentModel; using System.Windows.Forms; [TypeConverter(typeof(ExpectationResultConverter))] public enum ExpectationResult { [Description("-")] NoExpectation,[Description("Failed")] Fail } class ExpectationResultConverter : EnumConverter { public ExpectationResultConverter() : base( typeof(ExpectationResult)) { } public override object ConvertTo(ITypeDescriptorContext context,System.Globalization.CultureInfo culture,object value,System.Type destinationType) { if (destinationType == typeof(string)) { return "abc " + value.ToString(); // your code here } return base.ConvertTo(context,culture,value,destinationType); } } public class TestResult { public string TestDescription { get; set; } public ExpectationResult requiredExpectationResult { get; set; } public ExpectationResult NonrequiredExpectationResult { get; set; } static void Main() { BindingList<TestResult> list = new BindingList<TestResult>(); DataGridView grid = new DataGridView(); grid.DataSource = list; Form form = new Form(); grid.Dock = DockStyle.Fill; form.Controls.Add(grid); Application.Run(form); } }