Fill WPF listbox with string array

守給你的承諾、 提交于 2019-12-01 06:35:22

HTH:

    string[] list = new string[] { "1", "2", "3" };

    ObservableCollection<string> oList;
    oList = new System.Collections.ObjectModel.ObservableCollection<string>(list);
    listBox1.DataContext = oList;

    Binding binding = new Binding();
    listBox1.SetBinding(ListBox.ItemsSourceProperty, binding);

    (listBox1.ItemsSource as ObservableCollection<string>).RemoveAt(0);

Just use (ItemSource as ObservableCollection)... to work with items, and not Items.Add etc.

If you only want to express it more elegantly, then perhaps this will work.

stringList.ForEach(item => listBox1.Items.Add(item));

use OberservableCollection

Okay.. if binding is not an option - and I would probably go that way if it was... then the only more efficient way to populate the listbox would be to do it in parallel.

(For this to work I am assuming you have the .Net 4 runtime, or the PLinq libraries installed)

The following code would show massive improvements on a multicore machine provided the collection of data was large enough to warrant the overhead of the initial setup. So this would only be viable for larger arrays.

Parallel.ForEach(list, r => destinationList.Items.Add(r));

Else I don't see anything wrong with your foreach loop.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!