views:

264

answers:

2

i need to fill a listbox with items one by one like the list to be filled with one item than after 1/5 sec an other item will be added to the list

any ideas how this could be done (in wpf)?

A: 

In the Loaded event of the window or control, execute the method to load the first item of data by calling the BeginInvoke method of the System.Windows.Threading.DispatcherObject for the UI element, and specify a System.Windows.Threading.DispatcherPriority of Background. When this method has finished generating the data and adding it to the list, add the same method to the Dispatcher’s queue recursively, each time adding just one item and then queuing the call to add the next one with a DispatcherPriority of Background.

private ObservableCollection<string> numberDescriptions;
// Declare a delegate to wrap the LoadNumber method
private delegate void LoadNumberDelegate(int number);
private void LoadNumber(int number)
{
// Add the number to the observable collection
// bound to the ListBox
numberDescriptions.Add("Number " + number.ToString());
if(number < 10000)
{
// Load the next number, by executing this method
// recursively on the dispatcher queue, with
// a priority of Background.
//
this.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new LoadNumberDelegate(LoadNumber), ++number);
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Initialize an ObservableCollection of strings
numberDescriptions =
new ObservableCollection<string>();
// Set it as the ItemsSource for the ListBox
listBox.ItemsSource = numberDescriptions;
// Execute a delegate to load
// the first number on the UI thread, with
// a priority of Background.
//
this.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new LoadNumberDelegate(LoadNumber), 1);
}

see WPF Recipes in C# 2008 Load the Items in a ListBox Asynchronously(pg 460)

ArsenMkrt
+1  A: 

If you bind the ListBox to an ObservableCollection<T>, you can only modify the collection from the UI thread. So you could use a DispatcherTimer, which raises the Tick event on the UI thread, or use a specialized collection like this one and fill it from another thread

Thomas Levesque