Key Issues for C # GUI Event Processing

Good afternoon,

I have some very simple GUI questions. First, with C #, how can we associate events with objects - I guess event handlers? If so, can each handler use separate code? - How can an event handler find objects with which it should work?

I have a general idea of ​​how this works in JAVA. Directing me to a link would be nice - I already trawled Google for answers to no avail.

Thanks a lot, J

+3
source share
4 answers

-, #, - ? , ?

, :

class A {
    public event EventHandler SomeEvent;
}

class B {
    public B(A a) {
        a.SomeEvent += (sender, e) => { Console.WriteLine("B handler"); };
    }
}

class C {
    public C(A a) {
        a.SomeEvent += (sender, e) => { Console.WriteLine("C handler"); };
    }
}

, ?

, . EventHandlers, , (. Delegate.GetInvocationList). :

class EventHandler {
    LinkedList<Action<object, EventArgs>> subscribers =
        new LinkedList<Action<object, EventArgs>>();

    public void Add(Action<object, EventArgs> f) {
        subscribers.AddLast(f);
    }

    public void Remove(Action<object, EventArgs> f) {
        subscribers.Remove(f);
    }

    public void Invoke(object sender, EventArgs e) {
        foreach(Action<object, EventArgs> f in subscribers)
            f(sender, e);
    }
}

( . , , . / Voodoo.)

, , .

+5

Visual Studio, GUI. "", . , IDE .

    private void button_Click(object sender, EventArgs e)
    {
        //sender is the object which actually raised the event
        ((Button)sender).Text = "Clicked Me";
    }

( *.Designer.cs)

    button.Click += new System.EventHandler(this.button_Click);
+3

- , :

myButton.Click += new EventHandler(myEventHandler);

, , ( myEventHandler.

, ( ).

, MSDN : .

+3

, . WPF XAML:

<Button Click="HelloWorldClickEventHandler">Hello World</Button>

// this is in your .cs code file
private void HelloWorldClickEventHandler(object sender, RoutedEventArgs e)
{
    // some code
}

WinForms :

public MyForm() {
    // ...
    HelloWorldButton.Click += new EventHandler(HelloWorldClickEventHandler);
}

private void HelloWorldClickEventHandler(object sender, EventArgs e)
{
    // some code
}

, IDE, Visual Studio, .

, ?

:

  • (WPF) (WinForms), (.. this.MyLabel ).

  • sender , . , .

+2

Source: https://habr.com/ru/post/1781460/


All Articles