在ASP.NET中使用DisplayNameAttribute

jle*_*bke 7 asp.net

我想将List绑定到网页上的GridView,但是覆盖属性名称通过注释显示的方式.我认为System.ComponentModel可以工作,但这似乎不起作用.这仅适用于Windows Forms吗?:

using System.ComponentModel;

namespace MyWebApp
{
    public class MyCustomClass
    {
        [DisplayName("My Column")]
        public string MyFirstProperty
        {
            get { return "value"; }
        }

    public MyCustomClass() {}
}
Run Code Online (Sandbox Code Playgroud)

然后在页面上:

protected void Page_Load(object sender, EventArgs e)
{
    IList<MyCustomClass> myCustomClasses = new List<MyCustomClass>
    {
        new MyCustomClass(),
        new MyCustomClass()
    };

TestGrid.DataSource = myCustomClasses;
TestGrid.DataBind();
Run Code Online (Sandbox Code Playgroud)

}

这将使用"MyFirstProperty"作为列标题而不是"我的列"进行渲染.这应该不起作用吗?

Rus*_*lan 2

恶魔大人说的话……

答案似乎是否定的,你不能。至少不是开箱即用的。

System.Web.UI.WebControls.GridView 使用反射属性的名称:

protected virtual AutoGeneratedField CreateAutoGeneratedColumn(AutoGeneratedFieldProperties fieldProperties)
{
    AutoGeneratedField field = new AutoGeneratedField(fieldProperties.DataField);
    string name = fieldProperties.Name; //the name comes from a PropertyDescriptor
    ((IStateManager) field).TrackViewState();
    field.HeaderText = name; //<- here's reflected property name
    field.SortExpression = name;
    field.ReadOnly = fieldProperties.IsReadOnly;
    field.DataType = fieldProperties.Type;
    return field;
}
Run Code Online (Sandbox Code Playgroud)

虽然 System.Windows.Forms.DataGridView 使用 DisplayName(如果可用):

public DataGridViewColumn[] GetCollectionOfBoundDataGridViewColumns()
{
    ...
    ArrayList list = new ArrayList();
    //props is a collection of PropertyDescriptors
    for (int i = 0; i < this.props.Count; i++)
    {
        if (...)
        {
            DataGridViewColumn dataGridViewColumnFromType = GetDataGridViewColumnFromType(this.props[i].PropertyType);
            ...
            dataGridViewColumnFromType.Name = this.props[i].Name;
            dataGridViewColumnFromType.HeaderText = !string.IsNullOrEmpty(this.props[i].DisplayName) ? this.props[i].DisplayName : this.props[i].Name;
        }
    }
    DataGridViewColumn[] array = new DataGridViewColumn[list.Count];
    list.CopyTo(array);
    return array;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,虽然您可以重写 CreateAutoGenerateColumn,但缺少的 DisplayName 和基础属性描述符都不会被传递,并且您无法重写 CreateAutoGenerateColumns(尽管您可以 CreateColumns)。

这意味着您必须自己或在其他地方迭代反射的属性。