在 WPF 应用程序中动态创建按钮列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27555996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically creating List of Buttons in WPF application
提问by sibe94
I'm about to develop my first WPF.
我即将开发我的第一个 WPF。
I want to get a list of buttons. The buttons get generated by ONE "Add"-button at the top of the WPF.
我想得到一个按钮列表。这些按钮由 WPF 顶部的一个“添加”按钮生成。
So when i press "Add" a new buttons comes up in the list.
因此,当我按“添加”时,列表中会出现一个新按钮。
First how i create the list? With a ListBox or a StackPanel? I think for the look a StackPanel would be nice but im not sure about how to add buttons there ...
首先我如何创建列表?使用 ListBox 还是 StackPanel?我认为 StackPanel 看起来不错,但我不确定如何在那里添加按钮......
And the other question: Normally, when i generate an object (i come from Java) each object gets a unique instance. But how i give every button a unique name?
另一个问题:通常,当我生成一个对象(我来自 Java)时,每个对象都会获得一个唯一的实例。但是我如何给每个按钮一个唯一的名字?
I hope you can help me
我希望你可以帮助我
回答by BradleyDotNET
Stop. Right now.
停止。马上。
Before you do anything, learn basic MVVM. WPF is notWinForms (or its Java equivalent). You shouldn't be programmatically altering the UI until you know when you should do that.
在你做任何事情之前,先学习基本的 MVVM。WPF不是WinForms(或其 Java 等价物)。在您知道何时应该这样做之前,您不应该以编程方式更改 UI。
Those buttons should represent data. That data should be in your view model somewhere. Then you would have an ItemsControllike this:
这些按钮应该代表数据。该数据应该在您的视图模型中的某个地方。然后你会有ItemsControl这样的:
<ItemsControl ItemsSource="{Binding MyCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button ... />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Now you can get all the unique info you need based on the bound object (no need for unique names). You can even make ItemsControluse a StackPanelas the underlying panel (incidentally, it does by default).
现在,您可以根据绑定对象获取所需的所有唯一信息(不需要唯一名称)。您甚至可以ItemsControl使用 aStackPanel作为底层面板(顺便说一下,默认情况下是这样)。
回答by Bruno Brant
Since you need dynamic behavior and this is your first WPF app, you should write this on the code behind.
由于您需要动态行为,而且这是您的第一个 WPF 应用程序,因此您应该将其写在后面的代码中。
Just name your StackPanelsomething (add the name attribute to it), and handle the click event in the button (just double click the button in the WPF visual editor).
只需命名您的StackPanel东西(向其添加 name 属性),并处理按钮中的单击事件(只需双击 WPF 可视化编辑器中的按钮)。
Inside the handler for the click event, you can do something like this:
在单击事件的处理程序中,您可以执行以下操作:
this.MyStackPanel.Children.Add(new Button());
Of course, to add behavior to that button, you can assign it to a variable and add the proper event handlers.
当然,要向该按钮添加行为,您可以将其分配给一个变量并添加适当的事件处理程序。

