关于相同的问题有更多的问题和文章,但我有几个相关的问题,希望得到一些答案。
-
我听说过两种方法来找到按钮并添加处理程序或使用接口(从这里检查两种方法)..
-
如果你可以用一些代码来说明'接口'选项,以及在哪里对接口文件进行分类,因为当我试图继承它时,它在页面中不可读!
我认为第二种方法更好。第一种选择是将一个页面与特定的母版页耦合在一起,这并不好。
所有文件都放在同一个文件夹中。
IPageInterface.cs:
namespace CallFromMasterPage
{
public interface IPageInterface
{
void DoSomeAction();
}
}
Default.aspx.cs:
namespace CallFromMasterPage
{
public partial class Default : System.Web.UI.Page, IPageInterface
{
public void DoSomeAction()
{
throw new NotImplementedException();
}
}
}
Site.Master.cs:
namespace CallFromMasterPage
{
public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Button1_Click(object sender, EventArgs e)
{
IPageInterface pageInterface = Page as IPageInterface;
if (pageInterface != null)
{
pageInterface.DoSomeAction();
}
}
}
}
还有其他方法。例如,你可以通过事件代理发布事件。
看从我的打开它将是最好的,如果你使用事件处理程序…甚至使用自定义委托。
这样的public delegate ReturnType MasterPageButtonHandler(CustomEventArgs ObjPriargs);
public event MasterPageButtonHandler MasterPagebuttonClick;
.
.
.
.
Button.click+=new EventHandler(Button1_Click);
.
.
.
protected void Button1_Click(Object sender,EventArgs e)
{
if(MasterPagebuttonClick!=null)
{
CustomEventArgs ObjPriargs=new CustomEventArgs();
ObjPriargs.Property1=SomeValu1;
ObjPriargs.Property2=SomeValu2;
MasterPagebuttonClick.Invoke(ObjPriargs);
}
}
.
.
.
public class CustomEventArgs
{
Public DataType Property1{get;set;}
Public DataType Property2{get;set;}
Public DataType Property3{get;set;}
}
.
.
.
// Now in your aspx Page
MyMaster m=Page.Master as MyMaster;
m.MasterPagebuttonClick+=new MasterPageButtonHandler(MasterPageHandler_Click);
.
.
.
protected void MasterPageHandler_Click(CustomEventArgs ObjPriargs)
{
//You code/////
}
通过这种方式提供了一些灵活性,例如如果将来您想在点击时传递一些数据游览内容页面,这很容易实现。
我有一个日历在我的MasterPage,但我需要使用这个日期绑定一个数据网格在ContentPage。
MasterPage html:
<asp:Calendar ID="calAgenda" DefaultView="Days" Format="dd/MM/yyyy" runat="server" BackColor="White" CssClass="templeteCalendar" Visible="false" OnSelectionChanged="calAgenda_SelectionChanged"></asp:Calendar>
ContentPage html:
<asp:TextBox runat="server" ID="txtFechaBusqueda" CssClass="form-control templeteLabel" MaxLength="10" />
MasterPage c# Code:
protected void calAgenda_SelectionChanged(object sender, EventArgs e)
{
TextBox txtCalendarDate = (TextBox)ContentPlaceHolder1.FindControl("txtFechaBusqueda");
txtCalendarDate.Text = calAgenda.SelectedDate.ToString().Substring(0, 10);
}
这里我们在ContentPage中使用了一个eventandler来捕捉MaserPage中的事件点击。
ContentPage c# Code:
Calendar btnCalendar = Master.FindControl("calAgenda") as Calendar;
btnCalendar.SelectionChanged += new EventHandler(btnCalendar_Click);
那么我们需要定义btnCalendar_Click函数
protected void btnCalendar_Click(object sender, EventArgs e)
{
DoSomething();
}