Dynamically creating List of Buttons in WPF application [closed]

筅森魡賤 提交于 2020-01-14 14:56:46

问题


I'm about to develop my first 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.

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

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?

I hope you can help me


回答1:


Stop. Right now.

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.

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>

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




回答2:


Since you need dynamic behavior and this is your first WPF app, you should write this on the code behind.

Just name your StackPanel something (add the name attribute to it), and handle the click event in the button (just double click the button in the WPF visual editor).

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.



来源:https://stackoverflow.com/questions/27555996/dynamically-creating-list-of-buttons-in-wpf-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!