开发者

How to add a UserControl into another UserControl?

I have a UserControl called UC_Widget, it inherits from System.Web.UI.UserControl and ITextControl. It also overrides the function AddParsedSubObject. When I use it like below, it runs well.

<uc1:UC_Widget ID="UC_Widget1" runat="server">
  hello world
</uc1:UC_Widget>

but, it come out a problem: if I want to use this control to contain another user control, how can i do for this?? many thx!

<uc1:UC_Widget ID="UC_Widget1" runat="server">
hello world
    <uc1:UC_Widget ID="UC_Widget2" runat="server">
     guy
    </uc1:UC_Widget>
</uc1:UC_Widget>

thx Nix,i have solved the problem by the AddParsedSubObject method.

protected override void AddParsedSubObject(object obj)
        {
            if (this.HasControls())
            {
                base.AddParsedSubObject(obj);
            }
            else if (obj is LiteralControl)
            {
                HtmlContent.Append(((LiteralControl)obj).Text);
                this.Text = HtmlContent.ToString();
            }
            else
            {
                string text1 = this.Text;

                UC_eClinicWidget tmp = obj as UC_eClinicWidget;
                if (tmp != null)
                {
                    HtmlContent.A开发者_如何学JAVAppend(GetControlHtml(tmp));
                    this.Text = HtmlContent.ToString();
                }
            }
        }


While there is probably a better design, this is still possible.

  1. First evaluate that you can't pull out the piece that repeats. In your example a piece that you could* pullout would be the text. If you can break your control into smaller pieces it will make your overall design less complicated.
  2. Make sure you define a stop condition. As with any recursion you have to make it stop or you will get a Stack Overflow :) .

Counter example to @Tom Vervoort

<asp:UpdatePanel>
    <ContentTemplate>
        <asp:UpdatePanel>
            <ContentTemplate>
                Hi there
            </ContentTemplate>
        </asp:UpdatePanel>
    </ContentTemplate>
</asp:UpdatePanel> 


This would cause an infinite loop... if UC_Widget contains another UC_Widget, then the inner UC_Widget would also contain a UC_Widget and so on. You'll need to come up with a better design.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜