Click here to Skip to main content
15,949,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all!

Im adding buttons dynamically into uniform grid. I like to know is it bossible to subribe each buttons click event individually?

Here is codesnippet

C#
private void FillUniformGrid()
{          
  //just for example. content could have X buttons 
  for (int i = 0; i < 10; i++)
  {
   Button Button = new Button();
   //How to make unique click event each button?                    
   Button.Click += new RoutedEventHandler(ButtonClickEvent);                                
   Button.Content = "Button " + i;
   uniGrid.Children.Add(Button);
  }            
}

//I always end up here with every button click
private void ButtonClickEvent(object sender, RoutedEventArgs e)
{
Button temp = sender as Button;
//...
}


ofcource I could use fixed amout of buttons and make event subcribing eg. in if statement (if i=x) but is there any other way to do it?

Hope you got idea :)

Cheers!
Posted
Comments
BillWoodruff 18-Aug-11 19:03pm    
Assuming you have a distinct event handler you want to attach to each button: you could get 'fancy' and have a Dictionary whose key was a Button and value was the executable procedure; you could get into on-the-fly code generation. But, most likely, the simple answer given to you by TheyCallMeMrJames will serve you well.
Sergey Alexandrovich Kryukov 19-Aug-11 0:16am    
Good idea. For the 'fancy', please see my solution, the second part of it referencing my article "Dynamic Method Dispatcher". Many say it's pretty interesting. :-)
--SA

Other than "if"? You could use "switch" ;)

No, if you want to use the same handler you're going to need to use some conditional statement to figure out which one was clicked.

You might want to look into the commanding pattern in WPF as this gives you further control over button state.

Cheers.
 
Share this answer
 
Comments
BillWoodruff 18-Aug-11 19:04pm    
Simple way is most often the best way. +5
paleGegg0 19-Aug-11 0:00am    
Thanks for the clarification and tips about commanding pattern! Things seems much clearer now :)
First, you can use different anonymous method to add to a invocation list of every button:

C#
Button.Click += (sender, eventArgs) => { /* all individual here :-) */ };


Anyway, from the body of each anonymous handler you can always call some common methods. Overall, this approach is the most convenient.

If you want to get fancy in the way Bill Woodruff mentioned in his comment, you can use my DynamicMethodDispatcher I offer in my article Dynamic Method Dispatcher[^]. With the dispatcher, you can use different ways of writing the handler. Please see; I provide good range of usage samples.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900