我在此 RelayCommand 中遇到 UI 刷新问题:
private RelayCommand _DeleteReferenceCommand;
public RelayCommand DeleteReferenceCommand
{
get
{
return _DeleteReferenceCommand ?? (_DeleteReferenceCommand = new RelayCommand(
() =>
{
//the 2 next lines trigger properties that will modify some components Visibility on the view
ReferencesGridWithPicsUC.TextReplacingGridView = "Deleting the reference. Please wait...";
ReferencesGridWithPicsUC.GridViewVisibility = false;
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; // mouse cursor change
//using multi-threading so that UI updates while a long process takes place in the background
Task.Run(() =>
{
Application.Current.Dispatcher.Invoke((new Action(() =>
{
System.Threading.Thread.Sleep(3000); // simulates a long process
ReferencesGridWithPicsUC.GridViewVisibility = true; // Sets the UI controls visibility back to previous state
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Hand; // Mouse cursor back to previous value
}
)));
}
);
},
() => { return ReferencesGridWithPicsUC.SelectedReference != null; }
));
}
}
具体来说,当我启动应用程序并第一次运行此代码时,它按预期工作(鼠标光标和控件在 sleep (3000)之前按预期更新,然后恢复正常。再次执行代码时,我可以看到该属性已正确更新 GridViewVisibility 。但是 UI 不再刷新:由 GridViewVisibility 更改触发的控件可见性未更新。另一方面,鼠标光标不断按预期更新......
如果有人能解决这个该死的难题,我会感激你的;)
最佳答案
您必须仅调用调度程序来更新 UI。
使用Task.Run
作为后台任务。
await Task.Run(() =>
{
Thread.Sleep(3000);
});
在异步委托(delegate)中
new RelayCommand(
async () =>
{
之后,您将返回 UI 线程,因此不再需要 Dispatcher。
关于c# - UI 线程未按预期刷新为 WPF 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38744387/