我有几个按钮,我将它们放入循环的 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);
}
}
我想知道点击了哪个按钮并为每个按钮做一些不同的事情。比如我有方法
private void buttonClicked(Button b)
我发送点击按钮的地方,检查它的类型、名称或 ID,然后做一些事情。 这可能吗?
最佳答案
将此添加到您的循环中:
bnt.Click += (source, e) =>
{
//type the method's code here, using bnt to reference the button
};
Lambda 表达式允许您在代码中嵌入匿名方法,以便您可以访问本地方法变量。您可以阅读更多关于它们的信息 here .
关于c# - 循环 C# WPF 中按钮的单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11687633/