【问题标题】:Transfer value to dynamically loaded web user control将值传递给动态加载的 Web 用户控件
【发布时间】:2012-04-20 12:17:01
【问题描述】:

我有 ASPX 页面,在预初始化时我会检查要加载的用户控件。

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

然后在页面加载时,我加载该控件

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

如何将动态加载的用户控件从 aspx 传输到 ascx?

【问题讨论】:

    标签: c# asp.net .net user-controls


    【解决方案1】:

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

    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!";
    }
    

    【讨论】:

      【解决方案2】:

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

      见:http://msdn.microsoft.com/en-us/library/31hxzsdw.aspx

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

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-09
          • 1970-01-01
          • 2010-09-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-13
          • 1970-01-01
          相关资源
          最近更新 更多