开发者

How to set Template in asp.net from cs file?

Is it possible to set ITemplate property of the control in cs file ?

In aspx file I can do it by for example:

<MyControl>
    <MyTemplate>
        <div>
        sample text, other controls
        </div>
    </MyTemplate>
</MyControl>

this div in real situation looks like this:

<div id="StatusBarDiv" runat="server" align="right">
    <table>
        <tr>
            <开发者_JS百科td>
                <dxe:ASPxLabel ID="Title" runat="server" Text="Records per page:">
                </dxe:ASPxLabel>
            </td>                    
            <td>
                <dxe:ASPxComboBox ID="cbxRecordsPerPage" ClientInstanceName="cbxRecordsPerPage" Width="50px" runat="server" SelectedIndex="<%#GetSelectedIndex()%>">
                    <Paddings PaddingBottom="0" PaddingTop="0" />
                    <Items>
                        <dxe:ListEditItem Text="10" Value="10" />
                        <dxe:ListEditItem Text="20" Value="20" />
                        <dxe:ListEditItem Text="30" Value="30" />
                        <dxe:ListEditItem Text="40" Value="40" />
                        <dxe:ListEditItem Text="50" Value="50" />
                    </Items>
                </dxe:ASPxComboBox>
            </td>
        </tr>
    </table>
</div>


It is indeed possible. You can assign an instance of a class implementing ITemplate to your template property in your code-behind file:

public class YourTemplate: ITemplate
{
    public void InstantiateIn(Control container)
    {
        HtmlGenericControl div = new HtmlGenericControl("div");
        div.InnerText = "sample text, other controls";
        container.Controls.Add(div);
    }
}

Then, in your MyControl class:

protected override void OnLoad(EventArgs e)
{
    MyTemplate = new YourTemplate();
}

EDIT: Since the content of your template is quite complex, it would not be very convenient to create its control tree by hand, as I did in the example above.

It would probably be best to host the control tree in a user control and load that control in the template using the LoadControl() method:

public class YourTemplate: ITemplate
{
    public void InstantiateIn(Control container)
    {
        Control userControl = container.Page.LoadControl("YourUserControl.ascx");
        container.Controls.Add(userControl);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜