【发布时间】:2011-02-05 15:24:11
【问题描述】:
我正在尝试创建一个非常简单的模板化控件。我以前从未这样做过,但我知道我过去创建的很多控件如果包含模板功能将会受益匪浅 - 所以我现在正在学习。
我的问题是我的模板是在页面上输出的,但我的属性值不是。所以我得到的只是我在模板中包含的静态文本。
我必须正确地做某事,因为控件不会导致任何错误,因此它知道我的公共财产存在。 (例如,如果我尝试使用 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>
【问题讨论】:
标签: c# asp.net templates custom-server-controls servercontrols