如何以编程方式创建 WPF 按钮和传递参数

How to Programatically Create WPF Buttons and Pass Parameters

如标题所示,我需要在 WPF 应用程序中以编程方式创建按钮,每个按钮都与 collection 中的 object 相关联,以便单击事件将使用 object作为参数。

例如:

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 标签,或者没有解决具体的实现auto-assigning object 作为调用点击事件时应该使用的参数。

我找到了一个令我满意的解决方案,所以我会回答我自己的问题,但如果其他人愿意,可以提出他们自己的解决方案。

我的解决方案涉及创建一个继承自 Button 的自定义按钮,该按钮具有在实例化时分配的可公开访问的 IFoo 对象。

class FooButton : Button
{
    public IFoo Foo { get; private set; }

    public FooButton(IFoo foo) : base()
    {
        Foo = foo;
    }
}

然后实例化此自定义按钮以代替 Button,并在此时分配 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
    }
}

我不知道这个解决方案的可扩展性如何。我不是 wpf 或 xaml 专家。我敢肯定,使用命令模式可以提供更大的灵活性,并且可以控制很多它做不到的事情,但是对于一种简单、快速的方法来做到这一点,这应该足够了。 :)