views:

1631

answers:

2

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?

Thanks!

A: 

If you used the Add Service Reference dialog in visual studio, your collection is presumably an ObservableCollection. You might want to look at merging your new items into this collection on your background thread manually. i.e. call your webservice, then add / remove / update the items in your original list to synchronise the lists. Don't rebind the whole list.

Steve Willcock
+2  A: 

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 -

Stan R.