在自定义控件中使用ITemplate

时间:2012-11-18 17:21:38

标签: c# asp.net

我试图找出是否可以在自定义控件中使用ITemplate接口。这是我到目前为止所做的。

public class Tooltip : Control
{
    public ITemplate ContentTemplate { get; set; }

    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        var ctrl = new HtmlGenericControl("a");

        if (ContentTemplate != null)
        {
            ContentTemplate.InstantiateIn(ctrl);
        }

        this.Controls.Add(ctrl);
    }
}

asp.net控件用法

<gc:Tooltip runat="server">
    <ContentTemplate>
        hello
    </ContentTemplate>
</gc:Tooltip>

这个想法是它应该返回类似这样的东西

<a>hello</a>

但结果看起来像这样

<ContentTemplate>
  hello
</ContentTemplate>
<a></a>

它包含模板标签,似乎忽略了我做的任何事情。

感谢任何建议

2 个答案:

答案 0 :(得分:0)

我认为你应该看看here,并按照他们已经说的那样行事。

你错过了这个:

  [
      PersistenceMode(PersistenceMode.InnerProperty),
      TemplateContainer(typeof(TemplateItem))
  ]

你也应该在课堂上设置这个部分:

[ParseChildren(true)]

答案 1 :(得分:0)

我从错误的类继承,当切换到WebControl时,它开始工作

public class Tooltip : WebControl