Reputation: 257
I have a problem with my UI not updating while executing a Command.
I've got an indeterminate ProgressBar which has it's visibility bound to the IsBusyIndicator-property in the ViewModel. A Command should now excecute a method and show the ProgressBar while computing, as shown in the codesnippett below. However, this doesn't work as I'd expect. The property is set to the correct value but the UI doesn't update to show the ProgressBar.
It works fine if I just set the IsBusyIndicator to true and do nothing else in the Command, so INotifyPropertyChanged and the Binding are working correctly.
void CommandExecute()
{
IsBusyIndicator = true;
// Do stuff that takes long
IsBusyIndicator = false;
}
It seems to me that the UI waits for the Command to finish before it updates the View. Is there a way to force the UI to update right away?
Thanks in advance, may the force be with you.
Upvotes: 6
Views: 2460
Reputation: 419
As others said here, it doesn't work since you're probably doing your work on the UI thread.
Here are the technical stuff:
When PropertyChanged of INotifyPropertyChanged is raised, the binding is scheduling a handler by invoking it in the dispatcher with BeginInvoke
, not immediately.
Since the UI thread is still running your long operation, handling the property change remains waiting on the dispatcher queue. That's why the change happens only when the command is done.
Upvotes: 2
Reputation: 2497
You can try the following:
private async void CommandExecute()
{
IsBusyIndicator = true;
await Task.Run(() => DoWork());
IsBusyIndicator = false;
}
This makes DoWork()
run on a separate thread. Generally, async void
methods are to be avoided, but they're OK if they're handling a UI event.
Upvotes: 3