将值传输到动态加载的Web用户控件

我有ASPX页面在preinit我检查whitch用户控件加载。

control = "~/templates/" + which + "/master.ascx"; 

然后在pageload上,我加载该控件

  Control userControl = Page.LoadControl(control); Page.Controls.Add(userControl); 

我怎样才能将动态加载的用户控件从aspx转移到ascx?

您可以创建由所有自定义控件实现的界面。 这样,您可以转换到该界面并使用它来传递数据。 考虑这个例子:

 public interface ICustomControl { string SomeProperty { get; set; } } 

……和你的控件:

 public class Control1 : Control, ICustomControl { public string SomeProperty { get { return someControl.Text; } set { someControl.Text = value; } } // ... } 

现在,你可以这样做:

 Control userControl = Page.LoadControl(control); Page.Controls.Add(userControl); if (userControl is ICustomControl) { ICustomControl customControl = userControl as ICustomControl; customControl.SomeProperty = "Hello, world!"; } 

您可以使用Page.Findcontrol(…)在父页面中获取控件。

请参阅: http : //msdn.microsoft.com/en-us/library/31hxzsdw.aspx

只需确保在代码中设置ID,即可访问它。 喜欢:

 Control userControl = Page.LoadControl(control); userControl.ID = "ctlName"; Page.Controls.Add(userControl); 

在控件类类型中强制转换,需要为控件创建公共属性(如果要将数据传输到控件)

 var userControl = (master)Page.LoadControl(control); userControl.yourpublicproperty ="some text"; Page.Controls.Add(userControl);