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?
Solution 1:
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
Solution 2:
Consider you have a StackPanel
named sp
for(int i=0; i<5; i++)
{
System.Windows.Controls.Button newBtn = new Button();
newBtn.Content = i.ToString();
newBtn.Name = "Button" + i.ToString();
sp.Children.Add(newBtn);
}
To remove button you could do
sp.Children.Remove((UIElement)this.FindName("Button0"));
Hope this help.