How to refresh an ItemsSource with Silverlight 3?


I have a Silverlight 3 application which calls a traditional .NET Web Service (asmx) to get a list of records and then display it in a ListBox control (lstRecords.ItemsSource = myRecords). Any records could be added or updated or deleted at anytime and I would like my UI (records displayed in the ListBox control) to reflect the latest change.

Right now, I have a System.Threading.Timer which calls every 5 seconds the WebService and update the lstRecords.ItemsSource. It sort of works, but it doesn't do exactly what I want. For instance, if a row is selected and the ItemsSource refreshed, I lose the selection.

I was wondering if there is a mechanism in Silverlight 3 to handle such thing. Do you have better suggestion on how I could accomplish that?


My suggestions is to follow the Model-View-ViewModel pattern. You should separate your web service as the model and your XAML as the View, the ViewModel should be the layer in between them. Have your View(XAML) bind to an ObservableCollection in your ViewModel and have your ViewModel call the WebService directly and then merge the result with your ObservableCollection. If you rebind your collection each time you will lose the binding state of your ListBox.

Here are some links for MVVM -