情景:代码动态生成的按钮,需要自定义点击事件。但是生成的点击事件的参数是固定的,如何才能传入自定义的参数?

Button btn = new Button()
{
    Content = "这是按钮",
    Margin = new Thickness(5),
};

btn.Click += btn_Click;

// 生成的点击事件的方法参数是固定的
private void btn_Click(object sender, RoutedEventArgs e)
{
    // 按钮执行的逻辑
}

下面使用Lambda表达式,实现往点击事件中传入自定义的参数:

Student s = new Student(); // 用于传入点击事件中
Button btn = new Button()
{
    Content = "这是按钮",
    Margin = new Thickness(5),
};

btn.Click += (e, a) => MyBtnClick(s);

// 点击事件可传入任意自定义参数
private void MyBtnClick(Student s)
{
    // 按钮执行的逻辑
}

重要的参考:

https://stackoverflow.com/questions/6457474/eventhandler-with-custom-arguments

【C#】往按钮事件中传递自定义参数

相关文章:

  • 2021-06-27
  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
  • 2021-05-29
  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
猜你喜欢
  • 2022-01-17
  • 2021-07-30
  • 2021-07-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案