Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill WPF listbox with string array

Tags:

c#

wpf

listbox

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.

like image 923
Archie Avatar asked Apr 29 '10 11:04

Archie


2 Answers

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

stringList.ForEach(item => listBox1.Items.Add(item));
like image 167
Bent Tranberg Avatar answered Nov 15 '22 20:11

Bent Tranberg


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.

like image 5
Andrew Avatar answered Nov 15 '22 21:11

Andrew