Click event for button in loop C# WPF
buttonclick, c#, wpf
Solution
Add this to your loop:
bnt.Click += (source, e) =>
{
//type the method's code here, using bnt to reference the button
};
Lambda expressions allow you to embed anonymous methods in your code so that you can access local method variables. You can read more about them here.
Problem
I have couple buttons which im putting in wrapPanel in loop: ``` for (int i = 0; i < wrapWidthItems; i++) { for (int j = 0; j < wrapHeightItems; j++) { Button bnt = new Button(); bnt.Width = 50; bnt.Height = 50; bnt.Content = "Button" + i + j; bnt.Name = "Button" + i + j; bnt.Click += method here ? wrapPanelCategoryButtons.Children.Add(bnt); } } ``` I want to know which button was clicked and do something different for each of them. For example ill have method ``` private void buttonClicked(Button b) ``` where ill send clicked button, check type, name or id of that and then do something. Is that possible?