开发者

Pass MasterPage ImageButton event to content Page

I have ImageButton in a MasterPage. I want the OnClick event to fire and be captured by the .ASPX page hosted inside the MasterPage?

MasterPage:

<asp:ImageButton ID="btnClear" OnClick="Clear_Click" 
 ImageUrl="images/Back_Icon_06.png" runat="server" AlternateText="Clear" 
 width="38"   heigh开发者_Go百科t="39"/>


The masterpage is actually a child of the page (in fact, it's a UserControl). We don't want the page to have to be aware of the intimate details of its child controls (thats why we delegate those aspects to those controls in the first place), so the correct approach would be to handle the click event on the master page and from there fire another event on the masterpage which the page handles:

Master:

public event EventHandler SomethingHappened;

protected void Button_Click(object sender, EventArgs e)
{
    OnSomethingHappened(EventArgs.Empty);
}

protected void OnSomethingHappened(EventArgs e)
{
    if(this.SomethingHappened != null)
    {
        this.SomethingHappened(this, e);
    }
}

Page:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    //allows us to change master pages
    if(this.Master is MyMaster)
    {
        ((MyMaster)this.Master).SomethingHappened += new EventHandler(HandleSomethingHappened);
    }
}

private void HandleSomethingHappened(object sender, EventArgs e)
{
    //deal with it
}


I would recommend specifying a strongly typed master page in your content page and exposing the event on the master page side

Here's a good MSDN reference

This is similar to what Rex M specified but just simplifies accessing the Master Page a little bit.

// Master Page Code
public event EventHandler ClearClick
{
   add
   {
      this.btnClear.Click += value;
   }
   remove
   {
      this.btnClear.Click -= value;
   }
}

// Content Page markup
<%@ Page  masterPageFile="~/MasterPage.master"%>

<%@ MasterType  virtualPath="~/MasterPage.master"%> 

// Content Page Code
protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    this.Master.ClearClick += new EventHandler(OnClearClick);
}

private void OnClearClick(object sender, EventArgs e)
{
   // Handle click here
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜