Creating a simple templated control. Having issues
I'm trying to create a really simple templated control. I've never done it before, but I know a lot of my controls I have created in the past would have greatly benefited if I included templating ability - so I'm learning now.
The problem I have is that my template is outputted on the page but my property value is not. So all I get is the static text which I include in my template.
I must be doing something correctly because the control doesn't cause any errors, so it knows my public property exists. (e.g. if I try to use Container.ThisDoesntExist it throws an exception).
I'd appreciate some help on this. I may be just being a complete muppet and missing something. Online tutorials on simple templated server controls seem few and far between, so if you know of one I'd like to know about it.
A cut down version of my code is below.
Many Thanks, James
Here is my code for the control:
[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);
}
}
Here is my code for the container:
[ToolboxItem(false)]
pu开发者_如何学运维blic class TemplatedControlContainer : Control, INamingContainer
{
private string myString;
public string MyString
{
get
{
return myString;
}
}
internal TemplatedControlContainer(string mystr)
{
this.myString = mystr;
}
}
Here is my mark up:
<my:TemplatedControl runat="server">
<ItemTemplate>
<div style="background-color: Black; color: White;">
Text Here: <%# Container.MyString %>
</div>
</ItemTemplate>
</my:TemplatedControl>
you should invoke method DataBind on your control.
one possibility is to add DataBind call in CreateChildControls()method:
protected override void CreateChildControls() { Controls.Clear();
theContainer = new TemplatedControlContainer("Hello World");
this.ItemTemplate.InstantiateIn(theContainer);
Controls.Add(theContainer);
this.DataBind();
}
精彩评论