Simon Voggeneder
Simon Voggeneder

Reputation: 387

Updating UI Elements from within a Command Action

If I update a UI element multiple times from within a command action, only the last change is shown. As far as I understand it this has to do with the fact that the command actions are not performed in the UI thread but I fail to understand how to correctly command the UI thread to update the control at the time I want it updated.

This is the situation:

A TextBlock and a Button bound to the values in the code-behind file (this is only for testing purposes, I use MVVM in production):

<TextBlock Text="{Binding Text}" />
<Button Content="Test"
        Command="{Binding Command}" />

Command is a simple RelayCommand executing the following action:

private void ChangeText()
{
    Text = "Text 1";

    Thread.Sleep(1000);

    Text = "Text 2";

    Thread.Sleep(1000);

    Text = "Text 3";
}

The program simply sleeps for the prescribed two seconds and displays Text 3 in the text box, the first two UI changes are ignored. I want it to first display Text 1, sleep for a second, display Text 2, sleep again for a second and then finally display Text 3.

I guess there is a very simple way to achieve this and but I haven't found a suitable answer so far here or anywhere else.

Upvotes: 1

Views: 240

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61339

On the contrary, command actions are performed on the UI thread unless moved otherwise, and that's your problem.

Thread.Sleep is blocking the UI thread, so it can't do anything to display the updates. Instead use Task.Delay so the method execution is no longer blocking the UI thread (this also prevents the application from appearing "frozen"):

private async void ChangeText()
{
    Text = "Text 1";
    await Task.Delay(1000);
    Text = "Text 2";
    await Task.Delay(1000);
    Text = "Text 3";
}

Upvotes: 3

Related Questions