Dynamically add multiple buttons to wpf window?

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

Leave a Comment