简体   繁体   中英

Fill WPF listbox with string array

Instead of adding each item one by one to the ListBox destinationList from the string array m_List like this:

foreach (object name in m_List)
{
    destinationList.Items.Add((string)name);
}

Is there any better way I can do it?

I don't want to bind the data to the destinationList since I want to delete some entries from the ListBox later on.

如果你只想更优雅地表达它,那么也许这会起作用。

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

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.

使用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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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