设置属性使用的类:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Utils
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class PropertyLableAttribute : Attribute
{
/// <summary>
/// 字段描述
/// </summary>
public String Description { get; set; }
/// <summary>
/// 字段位置
/// 用于获取类时,设置字段的默认显示顺序
/// </summary>
public int SortNum { get; set; }
/// <summary>
/// 字段是否显示
/// 某些不需要显示的属性可设置为False
/// </summary>
public PropertyShowType Visible { get; set; }
/// <summary>
/// 用于设置该属性的值可输入范围
/// 某些不需要显示的属性可设置为False
/// </summary>
public IList DataCheckList { get; set; }
}
public enum PropertyShowType : uint
{
Show = 1,
Hidden = 0,
NotAvailable = 2
}
}
建立Model类 PurchaseLedger如下:
//PurchaseLedger类
//采购订单号
[PropertyLabel(Description = "采购订单号", SortNum = 10, Visible = PropertyShowType.Show)]
public string Ebeln { get; set; }
//项目
[PropertyLabel(Description = "项目", SortNum = 20, Visible = PropertyShowType.Show)]
public string Ebelp { get; set; }
//计划行
[PropertyLabel(Description = "计划行", SortNum = 30, Visible = PropertyShowType.Show)]
读取属性值绑定给Gridview:
public static void SetColumnsByEntityLabelProps(this GridView gridView, Dictionary<String, PropertyLabelAttribute> dict)
{
foreach (KeyValuePair<String, PropertyLabelAttribute> pair in dict)
{
var col = gridView.Columns.ColumnByFieldName(pair.Key);
if (col != null)
{
col.Caption = pair.Value.Description;
col.VisibleIndex = pair.Value.SortNum;
col.Visible = pair.Value.Visible == PropertyShowType.Show;
}
}
}
调用:
var dict = PropertyLabelUtils.GetPropertyDictionary(typeof(PurchaseLedger));
gridView1.SetColumnsByEntityLabelProps(dict);