简体   繁体   English

C#.net使事件从Page冒泡到用户控件(子控件)

[英]C# .net bubble down an event from Page to usercontrol (child)

Can a usercontrol (child, doesStuff.ascx) page react to an event from Page (parent, page.aspx)? 用户控件(子级,stuff.ascx)页面可以对页面(父级,page.aspx)中的事件做出反应吗? I have a button on the parent page. 我在父页面上有一个按钮。 Onclick i'd like to fire an event on the child. Onclick我想向孩子触发一个事件。

doesStuff.ascx: doesStuff.ascx:

//something like this //这样的东西

((doesStuff)this.Page).someButtonControl.click;

// or // 要么

something.Click += new EventHandler(someReference???);

If i truly understand you, You can use delegate to this purpose. 如果我真正了解您,则可以为此目的使用委托。 In user control uc1: 在用户控件uc1中:

    public Action action;
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        action();
    }

And in the page: 并在页面中:

protected void Page_Load(object sender, EventArgs e)
    {
        uc1.action = someAction;
    }

    public void someAction()
    {
        //Do Some thing
    }

Child to Parent Bubble Up 孩子对父母的泡沫

If you want to pass argument from child control to parent, you can use CommandEventHandler . 如果要将参数从子控件传递给父控件,则可以使用CommandEventHandler

Parent ASPX 父ASPX

<%@ Register Src="~/DoesStuff.ascx" TagPrefix="uc1" TagName="DoesStuff" %>    
<!DOCTYPE html>    
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <form id="form1" runat="server">
        <uc1:DoesStuff runat="server" ID="DoesStuff"
            OnChildButtonClicked="DoesStuff_ChildButtonClicked" />
    </form>
</body>
</html>

Parent Code Behind 背后的父代码

public partial class Parent : System.Web.UI.Page
{
    protected void DoesStuff_ChildButtonClicked(object sender, EventArgs e) { }
}

Child ASCX 儿童ASCX

<asp:Button ID="BubbleUpButton" runat="server" 
    Text="Bubble Up to Parent" 
    OnClick="BubbleUpButton_OnClick" />

Child Code Behind 后面的子代码

public partial class DoesStuff : System.Web.UI.UserControl
{
    public event EventHandler ChildButtonClicked = delegate { };

    protected void BubbleUpButton_OnClick(object sender, EventArgs e)
    {
        // bubble up the event to parent. 
        ChildButtonClicked(this, new EventArgs());
    }
}

Parent to Child 父母对孩子

It is not a good practice in ASP.Net Web Form to calling one event to another event without underlying control. 在ASP.Net Web窗体中 ,没有基础控件就将一个事件调用到另一个事件不是一个好习惯。

Instead, you want to create a public method, and call it from Parent. 相反,您想创建一个公共方法,并从Parent调用它。 For example, 例如,

// Parent
public partial class Parent : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var doesStuff = DoesStuff1 as DoesStuff;
        if (doesStuff != null) DoesStuff1.DisplayMessage("Hello from Parent!");
    }
}

// Child
public partial class DoesStuff : System.Web.UI.UserControl
{
    public void DisplayMessage(string message)
    {
        ChildLabel.Text = message;
    }
}

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

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