【发布时间】:2009-08-28 01:35:05
【问题描述】:
我想截取页面上(众多)控件的OnInit。目的是在运行时设置控件的各种属性。拦截发生在控件的ViewState 跟踪开始之前至关重要,因为所讨论的属性值不会存储在ViewState 中(以节省空间)。
有许多简单的技术可以在运行时设置属性,但它们不能满足我的需要,因为它们发生在 ViewState 跟踪 Control 开始之后。 (这种技术的一个示例是在 Page 的 OnInit 方法期间循环通过 Page 的控件树中的控件。这为时已晚,因为 ViewState 跟踪已经在控件上开始,因为它们被添加到树中。)
我接近了一个完美的解决方案。我将以下内容放在.browser 文件中:
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.WebControl" adapterType="TestClassLibrary.TestWebControlAdapter, TestClassLibrary"/>
</controlAdapters>
</browser>
</browsers>
以下是TestWebControlAdapter的源码:
using System;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Adapters;
namespace TestClassLibrary
{
public class TestWebControlAdapter : WebControlAdapter
{
protected override void OnInit(EventArgs e)
{
if (this.Control is Button)
{
((Button)this.Control).Text = "Test Adapter";
}
base.OnInit(e);
}
}
}
我看到的问题是适配器无法堆叠,因此这将覆盖任何其他可能应用于此控件的适配器。
对于解决此问题的更好方法有什么想法吗?请注意,虽然它会起作用,但我考虑实际上在 Page 中添加一个 Init 事件处理程序,以便标记中的所有控件过多,并且需要更通用的解决方案。
【问题讨论】: