6

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.

3
  • The stuff that takes long should be executed on a different thread so the UI thread is free to update the UI. Can you show the code that is taking long? Ideally it should be async code Commented Jan 26, 2019 at 14:45
  • The "code that is taking long" is just a Method call on the backend. Right now the code is running synchronously, but the idea is to make it async in the near future. I was just looking for a temporary solution, but thanks anyway. Commented Jan 26, 2019 at 14:50
  • @BenJey, as long as CommandExecute() method is running on UI thread you can not do that. // Do stuff that takes long should be run on another thread. Commented Jan 26, 2019 at 15:04

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.