简体   繁体   English

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

[英]Transfer value to dynamically loaded web user control

I have ASPX page where on preinit i check whitch user control to load. 我有ASPX页面在preinit我检查whitch用户控件加载。

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

Then on pageload, i load that control 然后在pageload上,我加载该控件

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

How i can transfer dynamically loaded user control, from aspx to ascx? 我如何将动态加载的用户控件从aspx转移到ascx?

You can create an interface that is implemented by all your custom controls. 您可以创建由所有自定义控件实现的界面。 This way, you can cast to that interface and use it to pass your data through it. 这样,您可以转换到该界面并使用它来传递数据。 Consider this example: 考虑这个例子:

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

... and your controls: ......和你的控件:

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

    // ...
}

Now, you can do something like this: 现在,您可以执行以下操作:

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

if (userControl is ICustomControl)
{
    ICustomControl customControl = userControl as ICustomControl;
    customControl.SomeProperty = "Hello, world!";
}

You could use Page.Findcontrol(...) to get a control in the parent page. 您可以使用Page.Findcontrol(...)来获取父页面中的控件。

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

Just make sure you set the ID in the code, so you can access it. 只需确保在代码中设置ID,即可访问它。 Like: 喜欢:

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

cast in your control class type, you need to create public properties for controls (if you want to transfer data to controls) 在控件类类型中强制转换,需要为控件创建公共属性(如果要将数据传输到控件)

var userControl = (master)Page.LoadControl(control);

userControl.yourpublicproperty ="some text";

Page.Controls.Add(userControl);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM