在 C# WPF 中将按钮(或任何控件)添加到列表框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17746410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:14:47  来源:igfitidea点击:

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

c#.netwpf

提问by Slippy

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.

我想以一个按钮为例,并以编程方式将其添加到列表框,而不是在 xaml 中。

My current stategy for doing this is :

我目前这样做的策略是:

Button testButton = new Button();
listbox.Items.add(testButton);

回答by Rohit

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");
    }

回答by 123 456 789 0

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

ListBox 有一个 Items 集合属性,您可以向其中添加任何控件。

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.

Add 方法需要一个对象类型,因此它可以采用要在列表中显示的字符串、整数、类等数据类型。