views:

50

answers:

4

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 related I have to say that I don't know what Delegates are in C#.

Many Thanks

+3  A: 

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;
Randolpho
+1  A: 

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.

Tahbaza
A: 

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);
        }

    }
Auxiliary
+1  A: 

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.

Eric
Thanks. I needed this.
Auxiliary