2010-01-27 96 views
3

对于C#来说相对陌生,我最近一直在研究自定义事件,虽然我现在明白了设置自定义事件所需的基本部分,但我无法确定,其中每件都属于。具体来说,这是我想要做的。.NET自定义事件组织帮助

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

所以,我试图从树控件的“Drop”事件处理程序(在验证放置之后)激发自己的自定义事件。这个想法是,我的事件的订阅者将处理底层数据的重新排序。

我只是努力确定其中应该创建和/或使用每件事件机器。

如果有人能为我提供上述的基本样本,那会很棒。例如,可能是一个简单的示例,它可以在现有的button_click事件中设置并触发自定义事件。这似乎是我想要做的很好的模拟。另外,如果我对问题的处理看起来完全错误,那么我也想知道这一点。

回答

6

您需要为您的事件处理程序声明原型,并使用一个成员变量来存放已在该类中注册的事件处理程序,并拥有树视图。

// 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 
    } 

} 
+0

谢谢!这(完整的例子)正是我所需要的。通过一点按摩,我能够在我的应用程序的背景下得到这个工作。 – 2010-01-28 14:59:08

1

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

public event EventHandler Drop; 

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

如果你有一个自定义EventArgs类型,你要使用通用EventHandler<MyEventArgs>委托,而不是EventHandler

还有什么你不确定的吗?

+0

感谢您的意见,这很有帮助。不幸的是,我看不到森林里的路。我的错,不是你的... – 2010-01-28 14:57:53

+2

-1:这段代码不是线程安全的 - 如果在抛出'NullReferenceException'后会抛出未分配的drop。您应该首先将Drop事件分配给一个'EventHandler'委托。 – 2010-01-28 15:09:55