Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

c# - Dynamically add multiple buttons to wpf window?

how would i add multiple buttons to a window in c#? here's what i need to do... i'm getting multiple user values from a dictionary (within reason, only @ 5-6 values). for each value, i need to create a button. now, how do i name the button, not the text within the button? how do i define the "click" method for each button (they will all be different)? and how do i erase the button if i don't want it anymore?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would encapsulate the whole thing, there normally should be no point in naming the button. Something like this:

public class SomeDataModel
{
    public string Content { get; }

    public ICommand Command { get; }

    public SomeDataModel(string content, ICommand command)
    {
        Content = content;
        Command = command;
    }
}

Then you can create models and put them into a bindable collection:

public ObservableCollection<SomeDataModel> MyData { get; } =
     new ObservableCollection<SomeDataModel>();

Then you just need to add and remove items from that and create buttons on the fly:

<ItemsControl ItemsSource="{Binding MyData}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding Content}" Command="{Binding Command}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

For more info see relevant articles on MSDN:

Data Binding Overview
Commanding Overview
Data Templating Overview


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...