【问题标题】:Can an ASP.Net control be configued to accept ANY attributes, even ones not defined as properties in the class definition?可以将 ASP.Net 控件配置为接受任何属性,即使是未在类定义中定义为属性的属性?
【发布时间】:2009-10-25 01:47:31
【问题描述】:

是否可以将控件定义为具有未指定的属性集?例如:

<MyPrefix:MyControl SomeAttribute="SomeValue" runat="server"/>

我不想事先在控件类上为“SomeAttribute”定义一个属性。我真的很喜欢 HashTable 或其他类似的结构:

"SomeAttribute" => "SomeValue"

所以这个控件可以用在很多地方,其属性基本上是在运行时组成的。

我想知道是否有一些解析方法可以覆盖,它在解析时迭代属性。我可以:

  1. 查找具有名称的属性并设置它
  2. 如果我没有找到这样的属性,请将属性名称和值放入哈希表中

可能吗?

【问题讨论】:

  • 我的回答解决了你的问题吗?

标签: asp.net controls


【解决方案1】:

您想使用IAttributeAccessor 接口。

定义 ASP.NET 服务器控件使用的方法,以提供对在服务器控件的开始标记中声明的任何属性的编程访问。

示例控件:

using System;
using System.Collections.Generic;
using System.Web.UI;

namespace App_Code.Controls {
    public class OutputAttributesControl : Control, IAttributeAccessor {
        private readonly IDictionary<String, String> _attributes = new Dictionary<String, String>();

        protected override void Render(HtmlTextWriter writer) {
            writer.Write("Attributes:<br/>");
            if (_attributes.Count > 0) {
                foreach (var pair in _attributes) {
                    writer.Write("{0} = {1} <br/>", pair.Key, pair.Value);
                }
            } else {
                writer.Write("(None)");
            }
        }

        public String GetAttribute(String key) {
            return _attributes[key];
        }

        public void SetAttribute(String key, String value) {
            _attributes[key] = value;
        }
    }
}

调用:

<AppCode:OutputAttributesControl runat="server" attr="value" />

输出:

Attributes:
attr = value

注意事项:

似乎只在无法正常解析的属性上调用SetAttribute。这意味着您不会在代码中看到 id- 或 runat-attribute。分配的属性 (attr="") 显示为空字符串。数据绑定属性在设计模式下根本不显示,但在正常模式下工作(假设有人像往常一样调用 DataBind)。

【讨论】:

  • 问题是解析控件会抛出错误,因为有属性没有映射到属性。
  • Deane,这不是我看到的行为。我将编辑我的帖子以显示一个控件,该控件可以处理向其抛出的所有内容。
  • 这最终完美运行。如果某个属性有匹配的属性,它会将值分配给该属性。否则,它会调用 SetAttribute,你可以在那里做任何你想做的事情。
猜你喜欢
  • 2015-07-16
  • 1970-01-01
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多