如何构造遍历多个级别的委托事件

时间:2012-09-22 19:05:53

标签: c# .net events delegates

我正在构建一个c#/ .net网站。

该网站使用母版页和更新面板。

我有一种情况,我在页面中有一个usercontrol,需要更新母版页中的用户控件,反之亦然。

我知道如何在usercontrol和页面,或者usercontrol和母版页之间构建一个委托,但我不确定几件事,因为我对.net的了解并不是那么好。

1)如何在usercontrol之间构建委托 - >页面 - >母版页(2级) 2)相同的向后用户控制 - >母版页 - >页

我不确定是否可以共享1)和2)的任何组件。例如,单个委托事件跨越2个级别并且双向工作。

我很感激任何建议/例子。

提前致谢。

1 个答案:

答案 0 :(得分:2)

我不能确定你的问题,但也许你需要知道你可以在命名空间级别声明委托?

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

   public class MyClass
   {
      public event MyDelegate OnSomethingHappened;
   }
}

修改 我想我明白了一点......看看这是不是你想要的: 这是来自Site.Master页面的'.cs'文件的代码,以及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); }
        }
    }
}