开发者

C# - Adding an Event Handler for all instances of a class

开发者 https://www.devze.com 2023-01-14 12:50 出处:网络
I have to add an unknown number of buttons to a form in WPF (It\'s actually a toolbox whose element are loaded dynamically). I\'m looking for a way to make one event handler for all of these instances

I have to add an unknown number of buttons to a form in WPF (It's actually a toolbox whose element are loaded dynamically). I'm looking for a way to make one event handler for all of these instances. Is this possible? And they're not exactly just buttons, It's 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 it helps or is somehow relat开发者_开发百科ed I have to say that I don't know what Delegates are in C#.

Many Thanks


You can attach the same event handler to many events.

For example:

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


How stupid of me to answer my own question. I figured it out like this: I could add the event handler inside the class itself for all instances. Duh!! Here's 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);
        }

    }


And yes, you should be able to access custom properties on your derived button class, assuming the methods/properties are public. The method signature for the event handler most likely includes Handler(object sender, EventArgs e) in which case you can cast sender to the type of your derived button.


You could implement a class factory class to both instantiate and configure each of your button instances (in your case add the event handler association) as you need them. This will allow you to write the configuration code in one place and ensure that the buttons are instantiated with the correct setup every time.

0

精彩评论

暂无评论...
验证码 换一张
取 消