c# - 如何使用 INamingContainer 创建自定义控件?

标签 c# asp.net controltemplate naming-containers

我正在尝试以下操作:

[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateContainer(typeof(TemplateContainer))]
public virtual ITemplate LayoutTemplate { get; set; }

protected void Page_Init(object sender, EventArgs e)
{
    this.Controls.Clear();

    if (LayoutTemplate != null)
    {
        var data = Enumerable.Range(0, 10);

        foreach (int index in data)
        {
            TemplateContainer container = new TemplateContainer(index);

            LayoutTemplate.InstantiateIn(container);

            this.Controls.Add(container);
        }
    }
}

我的容器类:

public class TemplateContainer : Control, INamingContainer
{
    public int Index { get; set; }

    internal TemplateContainer(int index)
    {
        this.Index = index;
    }
}

还有我的标记:

<uc:TemplateControl ID="ucTemplateControl" runat="server">
    <LayoutTemplate>
        <b>Index:</b>
        <asp:TextBox ID="Literal1" runat="server"
            Text='<%# Container.Index %>'
            ReadOnly="true" />
        <br />
    </LayoutTemplate>
</uc:TemplateControl>

但是由于某些原因 Container.Index 没有呈现任何值,只是空的。正在创建 10 个控件,但没有一个显示值。

我做错了什么?我该如何修复它才能显示 Index 值?

我尝试了类似于 MSDN 示例的东西:

最佳答案

要绑定(bind)您需要调用自定义控件的DataBind 方法的值。

打电话

ucTemplateControl.DataBind();

从页面制作数据绑定(bind)到模板上。

关于c# - 如何使用 INamingContainer 创建自定义控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9797018/

相关文章:

c# - 从另一个类访问 GUI

asp.net - 不同国家的时区

c# - SQL Server 的输出参数未打印到 Web 表单

c# - 哪个是在 ASP.NET(C#) 中使用字符串的最佳实践

WPF:在 XAML 中更改 ComboBox 箭头按钮颜色

c# - 从 .NET 中的字符串获取 URL 参数

c# - NHibernate 从类生成映射?

c# - 如何使用一致的语法重写此 LINQ 表达式?

WPF 组合框 : how to set focus on it's togglebutton

c# - 如何应用TextBox控件模板?