[英]How to Programatically Create WPF Buttons and Pass Parameters
正如标题所示,我需要在 WPF 应用程序中以编程方式创建按钮,每个按钮与集合中的 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 标签,或者没有解决自动分配 object 作为参数的具体实现应该在点击事件被调用时使用。
我想出了一个我很满意的解决方案,所以我会回答我自己的问题,但如果他们愿意,其他人可以提出他们自己的解决方案。
我的解决方案包括创建一个继承自 Button 的自定义按钮,该按钮在实例化时分配了一个可公开访问的 IFoo object。
class FooButton : Button
{
public IFoo Foo { get; private set; }
public FooButton(IFoo foo) : base()
{
Foo = foo;
}
}
然后实例化此自定义按钮以代替 Button,并在那时分配 IFoo object。 单击按钮时,可以检索 IFoo object 并将其作为参数传递或按需要使用。
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 专家。 我确信使用命令模式提供了更多的灵活性和对许多事情的控制权,但是对于一个简单、快速的方法来做到这一点,这就足够了。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.