2012-09-22 33 views
0

我正在構建一個c#/ .net網站。如何構建遍歷多個級別的委託事件

該網站使用母版頁和更新面板。

我有一個情況,我在頁面中有一個用戶控件,需要更新母版頁中的用戶控件,反之亦然。

我知道如何在用戶控件和頁面之間,或用戶控件和母版頁之間構建一個委託,但我不確定一些事情,因爲我對.net的知識並不是很好。

1)如何構建用戶控件之間的委託 - >頁面 - >母版頁(2級) 2)同樣向後用戶控件 - >主頁 - >頁面

我不知道是否有任何1)和2)的組件可以共享。例如,跨越兩個級別並且雙向工作的單個委託事件。

我會很感激任何建議/例子。

在此先感謝。

回答

2

我不能太確定你的問題,但也許你需要知道你可以在命名空間級別聲明委託?

namespace MyNamespace 
{ 
    public delegate void MyDelegate(object sender, EventArgs e); 

    public class MyClass 
    { 
     public event MyDelegate OnSomethingHappened; 
    } 
} 

編輯 我想我明白一個好一點......看看這是你在找什麼: 這是代碼從」的.cs'一的Site.Master頁的文件,和一個WebUserControl ...該委託是全局在名稱空間中,在母版頁中,並且用戶控件聲明該委託類型的事件:

// MASTER PAGE 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace WebApplication4 
{ 
    public delegate void MyDelegate(object sender, EventArgs e); 

    public partial class SiteMaster : System.Web.UI.MasterPage 
    { 
     // Here I am declaring the instance of the control...I have put it here to illustrate 
     // but normally you have dropped it onto your form in the designer... 
     protected WebUserControl1 ctrl1; 

     protected void Page_Load(object sender, EventArgs e) 
     { 
      // instantiate user control...this is done automatically in the designer.cs page 
      // if you created it in the visual designer... 
      this.ctrl1 = new WebUserControl1(); 

      // start listening for the event... 
      this.ctrl1.OnSomethingHappened += new MyDelegate(ctrl1_OnSomethingHappened); 
     } 

     void ctrl1_OnSomethingHappened(object sender, EventArgs e) 
     { 
      // here you react to the event being fired... 
      // perhaps you have "sent" yourself something as an object in the 'sender' parameter 
      // or perhaps you have declared a delegate that uses your own custom EventArgs... 
     } 
    } 
} 

//WEB USER CONTROL 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace WebApplication4 
{ 
    public partial class WebUserControl1 : System.Web.UI.UserControl 
    { 
     public event MyDelegate OnSomethingHappened; 

     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 

     private void MyMethod() 
     { 
      // do stuff...then fire event for some reason... 
      // Incidentally, ALWAYS do the != null check on the event before 
      // attempting to launch it...if nothing has subscribed to listen for the event 
      // then attempting to reference it will cause a null reference exception. 
      if (this.OnSomethingHappened != null) { this.OnSomethingHappened(this, EventArgs.Empty); } 
     } 
    } 
} 
+0

謝謝。假設我在用戶控件上執行此操作,那麼如何在主頁面中使用它 - 與頁面中的方式相同? – dotnetnoob

+0

讓我知道如果這是訣竅:-) – dylansweb

+0

謝謝,這工作得很好。 – dotnetnoob