如何动态添加usercontrol [英] how to keep on adding a usercontrol dynamically

查看:81
本文介绍了如何动态添加usercontrol的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



是否可以在同一个用户控件(嵌套)中添加usercontrol到任何级别。就像使用loadcontrol(a.ascx)等一样.plz帮助..

hello all,

Is it possible to add usercontrol inside the same usercontrol (nesting) upto any level. Like by using loadcontrol("a.ascx") etc. plz help..

推荐答案

是的,但如果你要覆盖这个过程,你可能需要管理这个过程。渲染方法或为孩子们使用自定义集合。



您必须将控件添加到父级控件否则 Init 加载事件将无法在子控件中正确触发。



Yes, but you may have to manage the process if you're overriding the render methods or if using a custom collection for the children.

You have to add the controls to the parents Controls collection otherwise the Init and Load events wont fire properly in the child controls.

public List<control> MyChildren { get; set; }

public override void Load(object sender, EventArgs e)
{

  foreach(Control c in MyChildren)
    this.Controls.Add(c);

}
</control>





然后你可以渲染你的孩子。





Then you can render out your children.

public override void Render(HtmlWriter writer)
{

  writer.Write("<div>");

  foreach(Control c in MyChildren)
    c.Render(writer);

  writer.Write("</div>");

}





此方法允许您维护比简单的父控件更复杂的控件层次结构。 br $>


----------更新----------



MyChildren属性声明的工作方式与此相同:





This approach allows you to maintain more complex control hierarchies than simple parent, child controls.

---------- Update ----------

The MyChildren property declaration works exactly the same way as doing this:

private List<Control> _myChildren;

public List<Control> MyChildren
{
  get { return _myChildren; }
  set { _myChildren = value; }
} 





虽然对于控件集合,您可能希望保护该值并确保其实例化。 />




Although for a control collection you'd probably want to protect the value and ensure it's instantiated.

private List<Control> _myChildren;

public List<Control> MyChildren
{
  get { return _myChildren ?? (_myChildren = new List<Control>()); }
}


这篇关于如何动态添加usercontrol的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆