Sako73
Sako73

Reputation: 10137

WPF image visibility is not changing

I have the following method in my WPF project (.net 4):

private void MyMethod(){
    imgMyImage.Visibility = Visibility.Visible;
    DoWork();
    imgMyImage.Visibility = Visibility.Collapsed;
}

The image is in a DockPanel, and I want it to appear while the "DoWork()" method is being executed, but it does not change state until after the "MyMethod()" method exits. Can someone explain how to make this work correctly?

Thank you for any help.

Upvotes: 1

Views: 3351

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564403

Your "DoWork" method is blocking the UI thread. Until it completes, nothing in the UI will change (and the UI will remain unresponsive).

A better option is to push the DoWork into a background thread. For example, using the new Task framework in .NET 4, you could write this as:

private void MyMethod()
{
    imgMyImage.Visibility = Visibility.Visible;

    // Create a background task for your work
    var task = Task.Factory.StartNew( () => DoWork() );

    // When it completes, have it hide (on the UI thread), imgMyImage element
    task.ContinueWith( t => imgMyImage.Visibility = Visibility.Collapsed, 
            TaskScheduler.FromCurrentSynchronizationContext() );
}

Upvotes: 9

Related Questions