出于某些与业务相关的原因,我做了一个向导导航用户控件。非常简单:下一个/上一个/完成按钮。
使用此导航用户控件的每个父页面都有一个SaveData函数,该函数可以保存数据并执行其他一些操作。
当用户单击下一个/上一个/完成时,我想在重定向到另一个页面之前调用父的SaveData函数。我该怎么做?或者你能推荐一种更好的方法(请尽可能使用代码示例)?
提前致谢!
答案 0 :(得分:3)
UserControl 不应调用 Parent 的功能。这不是一个好的设计。
相反,您希望将事件从 UserControl 冒泡到父页面。
注意:我的项目命名空间是 DemoWebForm 。
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="MyUserControl.ascx.cs"
Inherits="DemoWebForm.MyUserControl" %>
<asp:Button runat="server" ID="NextButton"
OnClick="NextButton_Click" Text="Next" />
<asp:Button runat="server" ID="PreviousButton"
OnClick="PreviousButtonn_Click" Text="Previous" />
<asp:Button runat="server" ID="FinishButton"
OnClick="FinishButton_Click" Text="Finish" />
public partial class MyUserControl : System.Web.UI.UserControl
{
public event ClickEventHandler NextClicked;
public event ClickEventHandler PreviousClicked;
public event ClickEventHandler FinishClicked;
protected void NextButton_Click(object sender, EventArgs e)
{
if (NextClicked != null)
{
NextClicked(sender, e);
}
}
protected void PreviousButtonn_Click(object sender, EventArgs e)
{
if (PreviousClicked != null)
{
PreviousClicked(sender, e);
}
}
protected void FinishButton_Click(object sender, EventArgs e)
{
if (FinishClicked != null)
{
FinishClicked(sender, e);
}
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Parent.aspx.cs"
Inherits="DemoWebForm.Parent" %>
<%@ Register Src="MyUserControl.ascx" TagName="MyUserControl" TagPrefix="uc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<uc1:MyUserControl ID="MyUserControl1" runat="server"
OnNextClicked="MyUserControl1_NextClicked"
OnPreviousClicked="MyUserControl1_PreviousClicked"
OnFinishClicked="MyUserControl1_FinishClicked" />
<asp:Literal runat="server" ID="MessageLiteral" />
</form>
</body>
</html>
public partial class Parent : System.Web.UI.Page
{
protected void MyUserControl1_NextClicked(object sender,EventArgs e)
{
MessageLiteral.Text = "Next button was clicked";
}
protected void MyUserControl1_PreviousClicked(object sender, EventArgs e)
{
MessageLiteral.Text = "Previous button was clicked";
}
protected void MyUserControl1_FinishClicked(object sender, EventArgs e)
{
MessageLiteral.Text = "Finish button was clicked";
}
}
答案 1 :(得分:0)
您只需要委托:
public delegate void ClickEventHandler(object sender, EventArgs e);
public event ClickEventHandler NextClicked;