c# - UI 线程未按预期刷新为 WPF 表单

标签 c# wpf

我在此 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/

相关文章:

WPFToolkit 数据网格 : Combobox column does not update selectedvaluebinding immediately

wpf - 正确单击数据网格中的按钮时,Telerik RadGridView 选定项绑定(bind)不起作用

c# - 列表创建和对象初始化器

c# - 惰性 WPF 绑定(bind)

c# - 什么是 "handle"?

c# - WPF 应用程序无法启动

c# - 传递未知类型的参数

c# - Winform App - 网页交互

wpf - 为什么不应该将 UserControls 用作 ItemsSource?

c# - WPF 中的数独 - 我应该为表格使用什么基本元素?