在WPF应用程序中动态创建按钮列表 [英] Dynamically creating List of Buttons in WPF application

查看:673
本文介绍了在WPF应用程序中动态创建按钮列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将要开发我的第一个WPF.

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.

因此,当我按添加"时,列表中会出现一个新按钮.

So when i press "Add" a new buttons comes up in the list.

首先,我如何创建列表?使用ListBox或StackPanel?我认为从外观上来说StackPanel会不错,但是我不确定如何在其中添加按钮...

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 ...

另一个问题:通常,当我生成一个对象(我来自Java)时,每个对象都会获得一个唯一的实例.但是我如何给每个按钮一个唯一的名称?

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?

希望你能帮助我

推荐答案

停止.现在.

在进行任何操作之前,请学习基本的MVVM. WPF是 not WinForms(或其Java等效语言).除非您知道何时应该这样做,否则不应该以编程方式更改UI.

Before you do anything, learn basic MVVM. WPF is not WinForms (or its Java equivalent). You shouldn't be programmatically altering the UI until you know when you should do that.

这些按钮应代表数据.这些数据应该在您的视图模型中的某个地方.然后您将有一个ItemsControl像这样:

Those buttons should represent data. That data should be in your view model somewhere. Then you would have an ItemsControl like this:

<ItemsControl ItemsSource="{Binding MyCollection}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button ... />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

现在,您可以根据绑定对象获得所需的所有唯一信息(无需唯一名称).您甚至可以使ItemsControl使用StackPanel作为基础面板(顺便说一下,默认情况下也是如此).

Now you can get all the unique info you need based on the bound object (no need for unique names). You can even make ItemsControl use a StackPanel as the underlying panel (incidentally, it does by default).

这篇关于在WPF应用程序中动态创建按钮列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆