C # - Adding an event handler for all instances of the class

I need to add an unknown number of buttons to a form in WPF (this is actually a toolbox whose element is loaded dynamically). I am looking for a way to make one event handler for all of these instances. Is it possible? And these are not just buttons, this is a class that inherits the Button class and has some other member variables. Will I be able to access these variables in such an event handler for each instance. If this helps or is somehow related, I must say that I do not know what the delegates in C # are.

Many thanks

+3
source share
4 answers

How stupid for me to answer my question. I understood this as follows: I could add an event handler inside the class itself for all instances. Duh !! Here is the code:

public class Tool_Button:Button{
        public String tool_name;
        public Tool_Button(String toolname) {
            this.Width = 32;
            this.Height = 32;
            this.BorderBrush = Brushes.Gray;
            tool_name = toolname;
            this.Background = new ImageBrush(new BitmapImage(new Uri(tool_name)));
            this.Click += new RoutedEventHandler(Tool_Button_Click);
        }

        void Tool_Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(tool_name);
        }

    }
+3
source

You can associate the same event handler with many events.

For instance:

var handler = new MyEventHandler(MyMethod);
obj1.MyEvent += handler;
obj2.MyEvent += handler;
obj3.MyEvent += handler;
+5
source

, , , / . , , Handler(object sender, EventArgs e) , .

+2

factory , ( ) . , .

+1

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


All Articles