c# - 循环 C# WPF 中按钮的单击事件

标签 c# wpf buttonclick

我有几个按钮,我将它们放入循环的 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/

相关文章:

java - 应用内购买 - 如何处理第二次点击?

java - 通过按钮单击将数据从 fragment 传递到 fragment

c# - LINQ to Entities 无法识别 MVC 4 中的方法 'System.String ToString()' 方法

C# - 限制消息队列

c# - 当参数不是字符串时,不参数化 SQL 查询是否安全?

c# - WPF 执行两个交替的 UI 任务

c# - Response.Redirect 与查询字符串

c# - 为什么驱动程序开发使用 C 而不是 C#?

c# - TextBlock 不更新内容

c# - WPF应用程序关闭的原因是什么