20

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?

3 Answers 3

36

Consider you have a StackPanel named sp

for(int i=0; i<5; i++)
{
    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.

Sign up to request clarification or add additional context in comments.

Comments

36

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

9 Comments

Very WPFish solution. I like it. :)
Is there any way you can provide an example with real data? I'm very new to WPF and this seems a little over my head. Thanks
@Jlange: Please read the linked articles, they should give you all you need.
Your answer provides better and professional way to solve the problem. I preferred taking my time to go through the articles to understand this solution rather than running a loop to add controls. Cheers!
@sohaiby: It is crucial for using the framework effectively to understand the various WPF concepts, so i appreciate it when people take the time to learn it properly; makes it easier for everyone involved :)
|
14

Xaml code:

<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
  <UniformGrid x:Name="grid">

  </UniformGrid>
</Window>

Code-behind:

public MainWindow()
{
  InitializeComponent();

  for (int i = 0; i < 10; ++i)
  {
    Button button = new Button()
      { 
        Content = string.Format("Button for {0}", i),
        Tag = i
      };
    button.Click += new RoutedEventHandler(button_Click);
    this.grid.Children.Add(button);
  }
}

void button_Click(object sender, RoutedEventArgs e)
{
  Console.WriteLine(string.Format("You clicked on the {0}. button.", (sender as Button).Tag));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.