【问题标题】:How to Programatically Create WPF Buttons and Pass Parameters如何以编程方式创建 WPF 按钮和传递参数
【发布时间】: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


    【解决方案1】:

    我的解决方案包括创建一个继承自 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 专家。我确信使用命令模式提供了更多的灵活性和对许多事情的控制权,但是对于一个简单、快速的方法来做到这一点,这就足够了。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-25
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 2018-06-14
      相关资源
      最近更新 更多