繁体   English   中英

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

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

用户控件(子级,stuff.ascx)页面可以对页面(父级,page.aspx)中的事件做出反应吗? 我在父页面上有一个按钮。 Onclick我想向孩子触发一个事件。

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
    }

孩子对父母的泡沫

如果要将参数从子控件传递给父控件,则可以使用CommandEventHandler

父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>

背后的父代码

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

儿童ASCX

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

后面的子代码

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());
    }
}

父母对孩子

在ASP.Net Web窗体中 ,没有基础控件就将一个事件调用到另一个事件不是一个好习惯。

相反,您想创建一个公共方法,并从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;
    }
}

暂无
暂无

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

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