C# 如何以编程方式创建WPF按钮并传递参数
正如标题所示,我需要通过编程在WPF应用程序中创建按钮,每个按钮都与集合中的对象关联,以便单击事件将该对象用作参数 例如:C# 如何以编程方式创建WPF按钮并传递参数,c#,wpf,button,parameter-passing,C#,Wpf,Button,Parameter Passing,正如标题所示,我需要通过编程在WPF应用程序中创建按钮,每个按钮都与集合中的对象关联,以便单击事件将该对象用作参数 例如: public FooWindow(IEnumerable<IFoo> foos) { InitializeComponent(); foreach(var foo in foos) { // Button creation code goes here, using foo // as the param
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
}
publicfoos窗口(IEnumerable foos)
{
初始化组件();
foreach(foos中的var foo)
{
//按钮创建代码在这里,使用foo
//作为单击按钮时的参数
按钮。单击+=按钮\u单击;
}
}
私有无效按钮\u单击(对象发送者,路由目标e)
{
//对关联的IFoo对象执行需要执行的操作
//使用调用此事件的按钮
}
到目前为止,我看到的所有解决方案都涉及到使用命令(这很好,但对于这个应用程序来说似乎过于复杂)、以不同寻常的方式使用xaml标记,或者没有解决在调用click事件时自动将对象指定为参数的具体实现
我想出了一个我很满意的解决方案,所以我会回答我自己的问题,但其他人可以根据自己的意愿提出自己的解决方案。我的解决方案包括创建一个自定义按钮,该按钮继承自在实例化时分配了可公开访问的IFoo对象的按钮
class FooButton : Button
{
public IFoo Foo { get; private set; }
public FooButton(IFoo foo) : base()
{
Foo = foo;
}
}
然后,将实例化此自定义按钮以代替按钮,并在此时指定IFoo对象。单击按钮时,可以检索IFoo对象并将其作为参数传递,或者根据需要使用
public FooWindow(IEnumerable<IFoo> foos)
{
InitializeComponent();
foreach(var foo in foos)
{
var button = new FooButton(foo);
button.Click += Button_Click;
// Add the button to your xaml container here
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if(sender is FooButton button)
{
// Do what you need to do here, using button.Foo as
// your parameter
}
}
publicfoos窗口(IEnumerable foos)
{
初始化组件();
foreach(foos中的var foo)
{
var按钮=新的FooButton(foo);
按钮。单击+=按钮\u单击;
//在此处将按钮添加到xaml容器
}
}
私有无效按钮\u单击(对象发送者,路由目标e)
{
如果(发送者是FooButton按钮)
{
//使用button.Foo作为
//你的参数
}
}
我不知道这个解决方案有多大的可扩展性。我不是wpf或xaml专家。我确信,使用命令模式可以在许多事情上提供更大的灵活性和控制能力,但对于一种简单、快速的方法来说,这就足够了。:)