开发者

WPF Changing Button Properties after clicked

开发者 https://www.devze.com 2023-02-05 22:27 出处:网络
My app has a UserControl that wraps a ServiceController to expose start/stop/restart win service functionality to the user. My concern at the moment is restarting. It takes a small amo开发者_StackOver

My app has a UserControl that wraps a ServiceController to expose start/stop/restart win service functionality to the user. My concern at the moment is restarting. It takes a small amo开发者_StackOverflowunt of time and I want to reflect the restarting status inside of the control. This is roughly what I have for the restart button click handler

private void RestartButton_Click(object sender, RoutedEventArgs e)
{
    startStopButton.Visibility = Visibility.Hidden;
    restartButton.Visibility   = Visibility.Hidden;
    statusTextBlock.Text = "Restarting...";

    Controller.Stop();
    Controller.WaitForStatus(ServiceControllerStatus.Stopped);
    Controller.Start();
    Controller.WaitForStatus(ServiceControllerStatus.Running);

    startStopButton.Visibility = Visibility.Visible;
    restartButton.Visibility   = Visibility.Visible;

    statusTextBlock.Text = Controller.Status.ToString();
}

Even when I step through the debugger I don't see these changes reflected in the application. Must be something that I'm missing. Also, I've tried disabling the buttons instead of hiding them and that does not work either.


You're doing everything on the UI thread, so the UI isn't updated until this code completes. You should do the heavy lifting on a background thread. The BackgroundWorker component makes this easy:

private void RestartButton_Click(object sender, RoutedEventArgs e)
{
    startStopButton.Visibility = Visibility.Hidden;
    restartButton.Visibility   = Visibility.Hidden;
    statusTextBlock.Text = "Restarting...";

    var backgroundWorker = new BackgroundWorker();

    // this delegate will run on a background thread
    backgroundWorker.DoWork += delegate
    {
        Controller.Stop();
        Controller.WaitForStatus(ServiceControllerStatus.Stopped);
        Controller.Start();
        Controller.WaitForStatus(ServiceControllerStatus.Running);
    };

    // this delegate will run on the UI thread once the work is complete
    backgroundWorker.RunWorkerCompleted += delegate
    {
        startStopButton.Visibility = Visibility.Visible;
        restartButton.Visibility   = Visibility.Visible;

        statusTextBlock.Text = Controller.Status.ToString();
    };

    backgroundWorker.RunWorkerAsync();
}


That's because execution is happening in the UI thread. Your button won't update because between { and } the UI thread is busy doing your work and it cannot update the button.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号