.NET自定义事件的组织协助自定义、事件、组织、NET

2023-09-05 02:31:40 作者:时光少年依旧蓝

作为相对较新的C#中,我一直在研究自定义事件最近,虽然我觉得我现在明白需要设置一个自定义事件的基础件,我无法确定的其中的各一块属于。具体而言,这里就是我想要做的事情。

Being relatively new to C#, I've been researching custom events recently, and while I think I now understand the basic pieces required to setup a custom event, I'm having trouble determining where each piece belongs. Specifically, here's what I'm trying to do.

我有一个树控件,再presents内部数据结构的布局。当数据被重新布置在树(通过拖/放),我需要重新排列的基本数据结构相匹配。

I have a tree control that represents the layout of an internal data structure. When the data is rearranged in the tree (via drag/drop), I need to rearrange the underlying data structure to match.

所以,我试图从树控制的水滴事件处理程序中激发自己的,自定义事件(后我已经确认了下降)。这个想法是,用户到我的事件将处理基础数据的重新排序。

So, I'm attempting to fire my own, custom event from within the "Drop" event handler of the tree control (after I've validated the drop). The idea being that a subscriber to my event would handle the reordering of the underlying data.

我只是在努力确定的其中的每件大事机械应建立和/或使用。

I'm just struggling to determine where each piece of event machinery should be created and/or used.

如果有人可以提供我上述的基本样本,那简直太好了。举例来说,也许一个简单的例子,设置和从现有button_click事件中触发一个自定义事件。这似乎是一个很好的模拟什么,我试图做的。

If someone could provide me with a basic sample of the above, that'd be great. For instance, maybe a simple example that sets up and fires a custom event from within an existing button_click event. That would seem to be a good simulation of what I'm trying to do.

另外,如果我解决问题的方法似乎完全错了,我想知道也。

Also, if my approach to the problem seems completely wrong, I'd like to know that also.

推荐答案

您需要声明的原型事件处理程序,以及一个成员变量来保存已注册的类拥有树形视图的事件处理程序。

You need to declare the prototype for your event handler, and a member variable to hold event handlers that have been registered in the class owns the treeview.

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

}
 
精彩推荐
图片推荐