循环 C# WPF 中按钮的单击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11687633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Click event for button in loop C# WPF
提问by user13657
I have couple buttons which im putting in wrapPanel in loop:
我有几个按钮,我将它们放入 wrapPanel 循环中:
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?
在哪里发送点击的按钮,检查类型、名称或 ID,然后做一些事情。那可能吗?
采纳答案by Daniel
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.
Lambda 表达式允许您在代码中嵌入匿名方法,以便您可以访问本地方法变量。您可以在此处阅读有关它们的更多信息。
回答by Hinek
All methods you hook up to an event have an argument sender, it is the object, that triggered the event. So in your case sender the Button object that was clicked. You can just cast it like this:
您连接到事件的所有方法都有一个参数sender,它是触发事件的对象。因此,在您的情况下,发送方是单击的 Button 对象。你可以像这样投射它:
void button_Click(Object sender, EventArgs e)
{
Button buttonThatWasClicked = (Button)sender;
// your code here e.g. call your method buttonClicked(buttonThatWasClicked);
}
回答by user13657
Thanks again for both responses - both works. There is full code maybe someone else could need that in future
再次感谢您的回复 - 两者都有效。有完整的代码,也许其他人将来可能需要它
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 += new RoutedEventHandler(bnt_Click);
/* bnt.Click += (source, e) =>
{
MessageBox.Show("Button pressed" + bnt.Name);
};*/
wrapPanelCategoryButtons.Children.Add(bnt);
}
}
}
void bnt_Click(object sender, RoutedEventArgs e)
{
Button buttonThatWasClicked = (Button)sender;
MessageBox.Show("Button pressed " + buttonThatWasClicked.Name);
}
By the way I'd like to know if that possible to (using wrapPanel) move buttons into another location ? I mean when i will click and drag button will be able to do that in wrappanel?
顺便说一句,我想知道是否可以(使用 wrapPanel)将按钮移动到另一个位置?我的意思是什么时候我将点击并拖动按钮将能够在 wrappanel 中做到这一点?

