4

我正在尝试创建一个非常简单的模板化控件。我以前从未这样做过,但我知道我过去创建的许多控件如果包括模板能力将会大大受益 - 所以我现在正在学习。

我遇到的问题是我的模板是在页面上输出的,但我的属性值不是。所以我得到的只是我在模板中包含的静态文本。

我必须正确地做某事,因为控件不会导致任何错误,所以它知道我的公共财产存在。(例如,如果我尝试使用 Container.ThisDoesntExist 它会引发异常)。

我很感激这方面的一些帮助。我可能只是一个完整的布偶,错过了一些东西。关于简单的模板化服务器控件的在线教程似乎很少,所以如果你知道一个我想知道它。

我的代码的精简版本如下。

非常感谢,詹姆斯

这是我的控件代码:

[ParseChildren(true)]
public class TemplatedControl : Control, INamingContainer
{
    private TemplatedControlContainer theContainer;

    [TemplateContainer(typeof(TemplatedControlContainer)), PersistenceMode(PersistenceMode.InnerProperty)]
    public ITemplate ItemTemplate { get; set; }

    protected override void CreateChildControls()
    {
        Controls.Clear();

        theContainer = new TemplatedControlContainer("Hello World");

        this.ItemTemplate.InstantiateIn(theContainer);

        Controls.Add(theContainer);
    }
}

这是我的容器代码:

[ToolboxItem(false)] 
public class TemplatedControlContainer : Control, INamingContainer
{
    private string myString;

    public string MyString
    {
        get
        {
            return myString;
        }
    }

    internal TemplatedControlContainer(string mystr)
    {
        this.myString = mystr;
    }
}

这是我的标记:

<my:TemplatedControl runat="server">
    <ItemTemplate>
        <div style="background-color: Black; color: White;">
            Text Here: <%# Container.MyString %>
        </div> 
    </ItemTemplate>
</my:TemplatedControl>
4

1 回答 1

1

您应该在控件上调用方法 DataBind。

一种可能性是在 CreateChildControls() 方法中添加 DataBind 调用:

受保护的覆盖无效 CreateChildControls() { Controls.Clear();

    theContainer = new TemplatedControlContainer("Hello World");

    this.ItemTemplate.InstantiateIn(theContainer);

    Controls.Add(theContainer);

    this.DataBind();

}
于 2010-04-09T16:07:43.803 回答