如何将自定义枚举描述绑定到DataGrid
问题:我有一个枚举类型,其中包含以下样式的描述标记:[URL =“http://xml.indelv.com/data-binding-enum.html”]描述标记教程[/ URL]。 我有一个Windows SQL Server数据库,我从中拉取数据(作为整数然后castine到枚举),然后绑定到数据网格。 我想在枚举类型中显示与其关联的描述标签,而不是拉动和包装枚举类型。
这是ASP –
<asp:HyperLinkField DataNavigateUrlFields="statementID" DataNavigateUrlFormatString="~/Gateway/Statements/Update.aspx?statementID={0}" NavigateUrl="~/Gateway/Statements/Update.aspx" HeaderText="Edit" Text="" /> There are no statements to display.
这是绑定的代码 –
[码]
private void BindData() { IStatementDao statementDao = DaoFactory.GetStatementDao(); List statements; if (Page.Request.RawUrl.Contains("Gateway")) { statements = statementDao.GetAll(); StatementGrid.HeaderStyle.CssClass = "GatewayGridHeader"; StatementGrid.AlternatingRowStyle.CssClass = "GatewayGridAlternatingRow"; } else { // This should never be reached but it keeps the compiler happy!! statements = statementDao.GetAll(); } StatementGrid.DataSource = statements; StatementGrid.DataBind(); DisplayTypeDescriptors(); }
[/码]
这是枚举的类 –
[码]
public enum TypeOfStatement { [EnumDescription("Dress Code")] DressCode = 1, [EnumDescription("Lunch Time")] LunchTime = 2, [EnumDescription("Footwarez")] Footware = 3, [EnumDescription("achtung")] Warning = 4, [EnumDescription("Banarna")] Banana = 5, [EnumDescription("Apfel")] Apple = 6 };c#
[/码]
显而易见的是,人们可以编写一个广泛的方法来做我想要的,但是有更简洁的方法吗?
动态包装它们并巧妙地改变你对SelectedItem(或你正在使用的任何东西)的处理
我的示例使用已存在的Description属性。
public class DescriptiveEnum where T: struct { private static readonly Dictionary descriptions = new Dictionary(); static DescriptiveEnum() { foreach (FieldInfo field in typeof(T).GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)) { descriptions.Add((T)field.GetRawConstantValue(), LookupName(field)); } } public readonly T Value; public DescriptiveEnum(T value) { this.Value = value; } public override string ToString() { string s; if (!descriptions.TryGetValue(this.Value, out s)) { // fall back for non declared fields s = this.Value.ToString(); descriptions[this.Value] = s; } return s; } private static string LookupName(FieldInfo field) { object[] all = field.GetCustomAttributes( typeof(DescriptionAttribute), false); if (all.Length == 0) return field.Name; // fall back else return ((DescriptionAttribute)all[0]) .Description; // only one needed } public static BindingList> Make( IEnumerable source) { var list = new BindingList>(); foreach (var x in source) list.Add(new DescriptiveEnum (x)); return list; } }
示例用法:
public enum Foo { [Description("flibble")] Bar, [Description("wobble")] Baz, // none present, will use the name Bat } Form f = new Form(); f.Controls.Add(new ListBox() { Dock = DockStyle.Fill, DataSource = DescriptiveEnum.Make( new Foo[] { Foo.Bar, Foo.Baz, Foo.Bat }), }); Application.Run(f);