繁体   English   中英

从其父页面调用UserControl方法

[英]Call UserControl method from Its parent page

我有一个这样的方法从其User Control调用Parent Page方法。这个“DisplayMessage”函数只接受一个字符串变量消息并在屏幕上显示它。 在用户控件中,我放置了一个文本框和一个按钮。 在Button的click事件中,我调用了上面讨论的Parent Page方法,我们使用Reflection并将文本框的值传递给方法,然后调用该方法并在屏幕上显示消息。

父页面:

public void DisplayMessage(string message)
{
   Response.Write(message);
}

用户控制:

protected void btnSend_Click(object sender, EventArgs e)
{
    this.Page.GetType().InvokeMember("DisplayMessage",System.Reflection.BindingFlags.InvokeMethod, null, this.Page, new object[] { txtMessage.Text });
}

这对我来说可以。

现在我需要的是,我必须从其父页面调用UserControl中存在的方法。

请建议我。 提前致谢。

无论您将控件放在页面上设置ID=""属性,都可以使用变量名称从页面中引用它。

因此,如果您的页面如下所示:

<my:UserControl runat="server" ID="myControl" />

然后你可以这样做:

myControl.MyControlMethod()

从父级在用户控件中调用的方法必须是公共的。 如果它是私有的或受保护的,则无法从父级调用该方法。

此外,不是通过反射调用页面函数,而是最好使用事件

我想我找到了最简单的方法

只需在用户控件的构造函数中传递父项的引用即可。

this.animationControl = new VideoEditor.AnimationControl(this);

并且在用户控件的构造函数中保存父表单在局部变量中的引用

public AnimationControl(Form1 form)
{
        _form1 = form;
        // other initialization stuff
}

现在通过这个局部变量'_form1'访问父类中的任何内容

_form1.MessageFromAnimationControl(choosenAnim);

访问子级中的父变量/方法或将子变量发送给父级。

我希望它会帮助别人:)

this.Page将为您提供页面对象的引用。

如果在基页中实现DisplayMessage,然后从中继承。

你可以把this.Page作为BasePage,然后调用方法:)

if(this.Page is BasePage)
{
   BasePage bs = this.Page as BasePage

   bs.DisplayMessage(....)   
}

暂无
暂无

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

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