C# .net 将事件从页面冒泡到用户控件 (child)

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

用户控件 (child、doesStuff.ascx) 页面能否对来自页面 (parent、page.aspx) 的事件作出反应?我在 parent 页面上有一个按钮。单击我想在 child.

上触发一个事件

doesStuff.ascx:

//像这样

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

// 或

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

如果我真的理解你,你可以使用委托来达到这个目的。在用户控件 uc1:

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

并且在页面中:

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

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

Child 到 Parent 冒泡

如果要将参数从 child 控件传递给 parent,可以使用 CommandEventHandler.

Parent 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 代码隐藏

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

Child ASCX

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

Child 代码隐藏

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 到 Child

在 ASP.Net Web 窗体 中,在没有底层控制的情况下将一个事件调用到另一个事件不是一个好习惯。

相反,您想创建一个 public 方法,并从 Parent 调用它。例如,

// 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;
    }
}