In my next presentation of MACO (my office developer community for sharing thought and knowledge about anything, just like MIX.. :D ), i am going to talk about Data-Driven Services in Silverlight 2.
I was trying to make a sample application using listbox, several textboxes and buttons and a progress bar when this trouble showed up. Apparently, my code is trying to update UI after i press the refresh button.
Generally speaking, silverlight doesn’t allow us to update any UI using a different thread than the UI thread it self, it calls “Cross-Thread”.
So, after searching a while using Microsoft latest invention “Bing”, finally i found a wise guy that had the same problem with me and share it on his blog.
How to do it, actually it is very simple. Just need two steps to overcome it.
Initialize the Action when the WCF service is ready to start retrieving the data. (By the way I'm using WCF service and M-V-VM pattern here, that is why you see the word “employeeViewModel” :P )
5: _vm = Resources["employeeViewModel"]
6: as EmployeeListViewModel;
7: _vm.OnRetrieveStart +=
8: new EventHandler(_vm_OnRetrieveStart);
9: _vm.OnRetrieveCompleted +=
10: new EventHandler(_vm_OnRetrieveCompleted);
1: void _vm_OnRetrieveStart(object sender, EventArgs e)
3: Action _onTimerAction = new Action(OnTimer);
4: Timer _timer = new Timer(
5: new TimerCallback(
6: delegate(object action)
11: null, 0, 100);
Do the UI updating or anything you want on the delegate method. As for me, the delegate method is updating the value of the progress bar which is updating the UI.
1: private void OnTimer()
3: progressBar.Value += 1;
4: if (progressBar.Value == progressBar.Maximum)
5: progressBar.Value = 0;
1: void _vm_OnRetrieveCompleted(object sender, EventArgs e)
3: progressBar.Value = progressBar.Maximum;
4: progressBar.Visibility = Visibility.Collapsed;
And after the retrieving process is completed, i just set the progress bar visibility to collapsed.
That’s all folks, hope this article is useful for you.
Source : Calling Web Services and Accessing UI from Timer Event in Silverlight