简体   繁体   English

将项目添加到列表 c# Wpf

[英]add items to a list c# Wpf

I have list, listbox, buttony textbox.我有列表、列表框、按钮文本框。

My idea is to do that by clicking on the button, the content of the text box is added to the list and then passing the data to a list box.我的想法是通过单击按钮来做到这一点,将文本框的内容添加到列表中,然后将数据传递到列表框。

My problem is if you add what I write, but the elements that are in the list box are overwritten with the new one that you insert.我的问题是,如果您添加我写的内容,但列表框中的元素会被您插入的新元素覆盖。 and I just want to add more articles.我只想添加更多文章。 to the list and to go to the list box.到列表并转到列表框。 Thank you very much for your answers.非常感谢您的回答。 This is the code of my button:这是我的按钮的代码:

private void button54_Click(object sender, RoutedEventArgs e)
{
    if (textBox3.Text != '')
    {
        List<Playlists> List1 = new List<Playlists>();
        List1.Add(new Playlists(textBox3.Text, @rutaalbum));
        lbPlaylist.ItemsSource = List1;
        ...
    }

    ...
}

I think you want to maintain a list and bind the list to a listbox.我认为您想维护一个列表并将该列表绑定到一个列表框。 Then be able to add to the list with a button.然后就可以用一个按钮添加到列表中了。 I found that I had to unbind by setting the ItemSource to null and rebind to get the new items added to the list to show up in the listbox.我发现我必须通过将 ItemSource 设置为 null 并重新绑定来取消绑定才能将新项目添加到列表中以显示在列表框中。

List<string> mylist = new List<string>();
        private void btnAddToList_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            mylist.Add(txtList.Text);
            ListBox1.ItemsSource = null;
            ListBox1.ItemsSource = mylist;
        }

To create a list :创建列表:

 List<string> mylist = new List<string>

To add items to the list :要将项目添加到列表:

 mylist.Add(textbox1.Text)

To add items to the ListBox from the list :要将项目从列表添加到ListBox

 foreach(string item in mylist)
 {
  ListBoxItem itm = new ListBoxItem();
  itm.Content = item;

  listbox.Items.Add(itm);
 }

Hope this helps you :)希望这对你有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM