你sleeping on UI thread冻结了你的 UI 线程,因此你没有看到 UI 上的任何更新。
控件的重绘由 UI 调度程序完成,但调度程序根据为任务设置的优先级执行操作。控件的重绘是在调度程序优先级设置为 Render 时完成的。按钮的设置内容在具有优先级渲染的调度程序上排队,但只有在所有具有较高优先级的任务完成后才会执行。
正如其他人所建议的那样,您应该将长时间运行的任务移到单独的线程上,但是在 UI 线程上休眠之前还有另一个解决方法来刷新 GUI。就像我提到的,一旦所有高于此的任务DispatcherPriority.Render完成,UI 将被重绘。所以,你可以做的是before sleeping on thread enqueue an empty delegate with render priority synchronously在force dispatcher to perform all tasks above and with priority render移动到下一个任务之前。这就是我的意思——
private void button3_Click(object sender, RoutedEventArgs e)
{
button3.Content = "Printing...";
button3.IsEnabled = false;
Dispatcher.Invoke((Action)(() => { }), DispatcherPriority.Render); <-- HERE
// button3.Refresh(); <-- After having extension method on UIElement.
Thread.Sleep(1000);
button3.IsEnabled = true;
button3.Content = "Print";
}
您也可以将此方法作为 UIElement 上的扩展方法 -
public static void Refresh(this UIElement uiElement)
{
uiElement.Dispatcher.Invoke((Action)(() => { }), DispatcherPriority.Render);
}
button3.Refresh()并在 UI 线程上睡觉之前调用。
但是,这也有一个缺点,因为它不仅会刷新您的 button3,而且会刷新 UI 上等待刷新的所有其他控件,因为调度程序将在移动到下一个任务之前完成所有优先级渲染或更高的任务。
但请始终牢记,永远不要在 UI 线程上睡觉。