如何在不从 WebControl 继承的控件中允许模板化控件

本文关键字:控件 模板化控件 继承 WebControl | 更新日期: 2023-09-27 18:19:50

在模板化服务器控件的所有示例中,包含模板的类继承自CompositeControl类,而类本身继承自WebControl类。

在我的应用程序中,我想在我的控件中使用模板,但也要从不同的类继承,该类不继承CompositeControlWebControl

"模板"可能意味着一大堆东西,但我问的是这样的代码:

[
Browsable(false),
DefaultValue(null),
Description("The Template for the content of the Control"),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateInstance(TemplateInstance.Single),
]
public ITemplate Content { get; set; }

并像这样 ASP.NET 代码:

<prefix:CustomControl ID="Control1" runat="server">
    <Content>
        <asp:Literal ID="ExampleContent" runat="server" Text="Look at me" />
    </Content>
</prefix:CustomControl>

但是,我注意到,当我从 WebControl 类继承时,对象中的ITemplate变量具有我期望的数据,而如果我不从 WebControl 继承,则这些变量具有NULL数据。

如何使用模板变量,同时从我选择的任何类继承?

如何在不从 WebControl 继承的控件中允许模板化控件

当然,

你必须从Control类继承,但魔术发生在ParseChildren属性上。要使用模板变量,必须将 ParseChildren 属性设置为 true

[ParseChildren(true)] // Don't treat tags within the Control as properties, but as Controls
public class CustomControl : Control
{
    // ...
}

我在检查WebControl类并阅读有关该属性的更多信息后发现了这一点。

ParseChildren 属性指定如何解释 ASP.NET 代码,其中的对象是表示控件 ( ParseChildren(false) ( 还是属性 ( ParseChilren(true) (。由于模板变量实际上是属性,因此必须将 ParseChildren 属性设置为 true 。遗憾的是,这也意味着不能在 ASP.NET 代码中混合使用模板化和非模板化控件,如下所示:

<prefix:CustomControl ID="Control1" runat="server">
    <Content>
        <asp:Literal ID="ExampleContent" runat="server" Text="Look at me" />
    </Content>
    <asp:Literal ID="ControlNonTemplate" runat="server" Text="This will not work (Parser error)" />
</prefix:CustomControl>