【发布时间】:2020-08-12 16:41:31
【问题描述】:
正如标题所示,我需要在 WPF 应用程序中以编程方式创建按钮,每个按钮与集合中的一个对象相关联,以便单击事件将使用该对象作为参数。
例如:
public FooWindow(IEnumerable<IFoo> foos)
{
InitializeComponent();
foreach(var foo in foos)
{
// Button creation code goes here, using foo
// as the parameter when the button is clicked
button.Click += Button_Click;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Do what you need to do with the IFoo object associated
// with the button that called this event
}
到目前为止,我看到的所有解决方案都涉及使用命令(这很好,但对于这个应用程序来说似乎过于复杂),以不寻常的方式使用 xaml 标记,或者没有解决将对象自动分配为的具体实现调用点击事件时应该使用的参数。
我找到了一个令我满意的解决方案,所以我会回答我自己的问题,但如果其他人愿意,他们可以提出自己的解决方案。
【问题讨论】:
标签: c# wpf button parameter-passing