Refresh WPF-Control by code

假如想象 提交于 2019-12-06 00:32:07

Since all that appears to happen on the UI-Thread the UI has no time to update in-between, you need to run your task on a background thread and change the UI again on completion (e.g. use a BackgroundWorker which already has a RunWorkerCompleted event).

e.g.

button.IsEnabled = false;
var bw = new BackgroundWorker();
bw.DoWork += (s, _) =>
{
    //Long-running things.
};
bw.RunWorkerCompleted += (s,_) => button.IsEnabled = true;
bw.RunWorkerAsync();

even better, instead of messing around with events, why not use ICommand binding and there you can implement CanExecute which you can return true/false depending on whether you want to enable/disable the button

Great example here on ICommand

You are setting the priority of a method to Render, which does not actually do any rendering.

I would say using an asynchronous call would be the best action to take here, giving the layout engine time to render:

private void buttonConnect_Click(object sender, RoutedEventArgs e)
{
    this.Cursor = Cursors.Wait; 
    buttonConnect.IsEnabled = false; 

    Action action = buttonConnect.Content.Equals("Connect") ? connect : disconnect;

    new Action(() => {
        action();
        Dispatcher.Invoke(() =>
            {
                buttonConnect.IsEnabled = true;
                this.Cursor = Cursors.Arrow;
            });
    }).BeginInvoke(null, null);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!