2010-01-27 98 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