简体   繁体   中英

Why control's visibility property doesn't update immediately?

I have a question on UIElement.Visibility Property.

The following code is executed when the 'StartAll' button is clicked:

private void butStartAllClick(object sender, RoutedEventArgs e)
    {
        butStartAll.Content = "Running";

        LEDInitializing.Visibility = Visibility.Visible;
        lblInitializing.Visibility = Visibility.Visible;

        Init();

        //...rest of code
    }

Init then starts up a lengthy initialization routine. My problem is that the visibility attribute is only modified at the end of the Init() method.

How do I get it to update immediately?

I have tried using the Dispatcher like so:

    LEDInitializing.Dispatcher.BeginInvoke(
                System.Windows.Threading.DispatcherPriority.Normal,
                                   new Action(
                                       delegate()
                                       {
                                           LEDInitializing.Visibility = Visibility.Visible;
                                       }
                                       ));

But this doesn't solve my problem.

Any assistance would be greatly appreciated :)

By running Init on the UI thread, you are preventing any of the UI changes you make from running until after it completes and butStartAllClick exits. Depending on what's in Init you may just be able to run it on a separate thread (4.5 here, use TaskFactory in 4.0):

private void butStartAllClick(object sender, RoutedEventArgs e)
{
    butStartAll.Content = "Running";

    LEDInitializing.Visibility = Visibility.Visible;
    lblInitializing.Visibility = Visibility.Visible;

    Task.Run(() =>
    {
        Init();
        //...rest of code
    });
}

If Init or the following code is doing anything that needs to interact with the UI then you'll need to break it up and use callbacks to the UI to do those updates as needed. The async/await pattern in 4.5 is usually the easiest way to do this but you can get the same effect in 4.0 with manually set up Task continuations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM