Creating a simple templated control. Having issues...

Posted by Jimock on Stack Overflow See other posts from Stack Overflow or by Jimock
Published on 2010-04-08T10:19:56Z Indexed on 2010/04/08 10:23 UTC
Read the original article Hit count: 371

Hi,

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)] 
public 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>

© Stack Overflow or respective owner

Related posts about c#

Related posts about custom-server-controls