我有几个按钮,我把它们放在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详细了解它们。

10-08 09:27