数据绑定枚举属性到网格并显示描述 [英] Data bind enum properties to grid and display description
问题描述
这是一个类似于如何绑定的问题DataGrid 的自定义枚举描述,但在我的情况下,我有多个属性.
This is a similar question to How to bind a custom Enum description to a DataGrid, but in my case I have multiple properties.
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
I'm binding a BindingList<TestResult> to a WinForms DataGridView (actually a DevExpress.XtraGrid.GridControl, but a generic solution would be more widely applicable). I want the descriptions to appear rather than the enum names. How can I accomplish this? (There are no constraints on the class/enum/attributes; I can change them at will.)
推荐答案
TypeConverter
通常会完成这项工作;这是一些适用于 DataGridView
的代码 - 只需添加您的代码以读取描述(通过反射等 - 我现在只是使用字符串前缀来显示自定义代码的工作).
A TypeConverter
will usually do the job; here's some code that works for DataGridView
- just add in your code to read the descriptions (via reflection etc - I've just used a string prefix for now to show the custom code working).
请注意,您可能也想覆盖 ConvertFrom
.转换器可以在类型或属性级别指定(以防您只希望它应用于某些属性),如果枚举不受您的控制,也可以在运行时应用.
Note you would probably want to override ConvertFrom
too. The converter can be specified at the type or the property level (in case you only want it to apply for some properties), and can also be applied at runtime if the enum isn't under your control.
using System.ComponentModel;
using System.Windows.Forms;
[TypeConverter(typeof(ExpectationResultConverter))]
public enum ExpectationResult
{
[Description("-")]
NoExpectation,
[Description("Passed")]
Pass,
[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);
}
}
这篇关于数据绑定枚举属性到网格并显示描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!