WPF 更新 UI 来自 RefreshEvent

WPF Update UI From RefreshEvent

我实际上尝试从外部 class 中的 RefreshEvent 更新 MainWindow UI。

我尝试了以下方法,但 UI 没有刷新。

 System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
 {
      foreach (OPCItem o in ((MainWindow)System.Windows.Application.Current.MainWindow).dgItems.Items)
      {
          if (o.ItemID == arg.items[i].OpcIDef.ItemID)
          {
              o.Value = Item.Value;
              o.DateTime = Item.DateTime;
              o.Quality = Item.Quality;

             ((MainWindow)System.Windows.Application.Current.MainWindow).dgItems.Items.Refresh();
           }
       }
 }));

要确保您的 ui 得到刷新,您应该使用 Dispatcher

public static class UiRefresh
{

    private static Action EmptyDelegate = delegate () { };


    public static void Refresh(this UIElement uiElement)
    {
        uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
    }
}

然后 yourElement.Refresh() 就可以了

调用 ((MainWindow)System.Windows.Application.Current.MainWindow).UpdateLayout() 应该可以解决问题