【问题标题】:How do I allow Templated Controls in a Control that doesn't inherit from WebControl?如何在不从 WebControl 继承的控件中允许模板化控件?
【发布时间】:2015-10-28 21:05:57
【问题描述】:

在所有的examples of Templated server controls中,包含模板的类继承自CompositeControl类,而CompositeControl类本身继承自WebControl类。

在我的应用程序中,我想要use Templates in my Control,但也继承自不同的类,该类既不继承自CompositeControl 也不继承自WebControl

“模板”可能意味着很多东西,但我问的是这样的代码:

[
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 继承,这些变量具有 @ 987654332@数据。

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

【问题讨论】:

    标签: c# asp.net custom-controls


    【解决方案1】:

    当然,您必须从 Control 类继承,但神奇的是 ParseChildren 属性。要使用模板变量,您必须将ParseChildren 属性设置为true

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

    我在检查了WebControl 类和reading more about the attribute 后发现了这一点。

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-07
      • 1970-01-01
      • 2010-11-10
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      相关资源
      最近更新 更多