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

Nov*_*ato 3 .net c# asp.net user-controls

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

 control = "~/templates/" + which + "/master.ascx";
Run Code Online (Sandbox Code Playgroud)

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

 Control userControl = Page.LoadControl(control);
 Page.Controls.Add(userControl);
Run Code Online (Sandbox Code Playgroud)

我如何将动态加载的用户控件从aspx转移到ascx?

npc*_*diu 5

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

public interface ICustomControl
{
    string SomeProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

......和你的控件:

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以执行以下操作:

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

if (userControl is ICustomControl)
{
    ICustomControl customControl = userControl as ICustomControl;
    customControl.SomeProperty = "Hello, world!";
}
Run Code Online (Sandbox Code Playgroud)