Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a button (or any control really) to a listbox in C# WPF?

Tags:

c#

.net

wpf

I know this probably simple, but I have been searching google, and I really haven't made much ground.

I would like to take a button for example, and add it to a listbox, programatically, not in the xaml.

My current stategy for doing this is :

Button testButton = new Button();
listbox.Items.add(testButton);
like image 229
Slippy Avatar asked Oct 22 '22 05:10

Slippy


2 Answers

Have you tried this...

 private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Button b = new Button();
        b.Content = "myitem";
        b.Click += new RoutedEventHandler(b_Click);
        listBox1.Items.Add(b);
    }

    void b_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Item CLicked");
    }
like image 197
Rohit Avatar answered Oct 24 '22 04:10

Rohit


ListBox has an Items collection property that you can add any control into it.

var listBox = new ListBox();
var button = new Button()
                        {
                         Content = "Click me"
                        };
var textBlock = new TextBlock()
                        {
                         Text = "This is a textblock"
                        };
 listBox.Items.Add(button);
 listBox.Items.Add(textBlock);

Add method is expecting an object type so it can take data types like strings, integer, classes that you want to show in the list.

like image 30
123 456 789 0 Avatar answered Oct 24 '22 04:10

123 456 789 0