.NET自定义事件组织帮助

作为C#的新手,我最近一直在研究自定义事件,虽然我认为我现在理解设置自定义事件所需的基本部分,但我无法确定每个部分所属的位置。 具体来说,这就是我想要做的。

我有一个树控件,表示内部数据结构的布局。 当数据在树中重新排列时(通过拖放),我需要重新排列基础数据结构以匹配。

所以,我试图从树控件的“Drop”事件处理程序中激活我自己的自定义事件(在我validation了drop之后)。 我的想法是我的事件的订阅者将处理底层数据的重新排序。

我只是在努力确定应该创建和/或使用每个事件机器的位置。

如果有人能为我提供上述基本样本,那就太好了。 例如,可能是一个简单的示例,用于在现有的button_click事件中设置和触发自定义事件。 这似乎是我正在尝试做的很好的模拟。

另外,如果我对这个问题的处理方法看起来完全错误,我也想知道。

您需要为事件处理程序声明原型,并且用于保存已在类中注册的事件处理程序的成员变量拥有树视图。

// this class exists so that you can pass arguments to the event handler // public class FooEventArgs : EventArgs { public FooEventArgs (int whatever) { this.m_whatever = whatever; } int m_whatever; } // this is the class the owns the treeview public class MyClass: ... { ... // prototype for the event handler public delegate void FooCustomEventHandler(Object sender, FooEventArgs args); // variable that holds the list of registered event handlers public event FooCustomEventHandler FooEvent; protected void SendFooCustomEvent(int whatever) { FooEventArgs args = new FooEventArgs(whatever); FooEvent(this, args); } private void OnBtn_Click(object sender, System.EventArgs e) { SendFooCustomEvent(42); } ... } // the class that needs to be informed when the treeview changes // public class MyClient : ... { private MyClass form; private Init() { form.FooEvent += new MyClass.FooCustomEventHandler(On_FooCustomEvent); } private void On_FooCustomEvent(Object sender, FooEventArgs args) { // reorganize back end data here } } 

一切都属于暴露事件的类:

 public event EventHandler Drop; protected virtual void OnDrop(EventArgs e) { if (Drop != null) { Drop(this, e); } } 

如果您有自定义EventArgs类型,则需要使用通用EventHandler委托而不是EventHandler

还有什么你不确定的吗?