Yuval Levy
Yuval Levy

Reputation: 2516

change UI wait 2000 milliseconds and change UI again

I want to show some text and a picture In a way that text will be visible for 2 seconds, and then the picture will replace it. Also in that time not to make the UI to be stuck.

I tried the following: In WPF UI:

            <Border x:Name="ComparisonResultImageBox" Visibility="Visible" Grid.Row="2" Grid.Column="2" Background="White" Margin="8,5,8,5">
                <Image x:Name="DiffrenceImage"></Image>
            </Border>

AND:

            <Border x:Name="LoadingComparisonResultLabel" Visibility="Collapsed" Grid.Row="2" Grid.Column="2" Background="White" Margin="0,5,8,5">
                <Label Content="Loading Comparison Result..." FontFamily="Open Sans" FontSize="13" ></Label>
            </Border>

Then in the code, when some button on the page get clicked I invoked the following method:

private void ClearComparePicture() {
    DiffrenceImage.Source = null;

    LoadingComparisonResultLabel.Visibility = Visibility.Visible;
    ComparisonResultImageBox.Visibility = Visibility.Collapsed;

    Thread.Sleep(2000);
    DiffrenceImage.Source = newBitmapImage;

    LoadingComparisonResultLabel.Visibility = Visibility.Collapsed;
    ComparisonResultImageBox.Visibility = Visibility.Visible;
}

The problem is that the text doesn't show during the sleep time....

Upvotes: 0

Views: 100

Answers (1)

Silas Reinagel
Silas Reinagel

Reputation: 4223

You shouldn't use any blocking calls (long running synchronous) on the UI thread.

The simplest change that might make this work is to use an async Task or async void.

private async Task ClearComparePicture() {
    DiffrenceImage.Source = null;    

    LoadingComparisonResultLabel.Visibility = Visibility.Visible;
    ComparisonResultImageBox.Visibility = Visibility.Collapsed;

    await Task.Delay(2000);
    DiffrenceImage.Source = newBitmapImage;

    LoadingComparisonResultLabel.Visibility = Visibility.Collapsed;
    ComparisonResultImageBox.Visibility = Visibility.Visible;
}

Upvotes: 3

Related Questions