WPF更新UI从RefreshEvent

Phi*_*795 2 c# wpf dispatcher

我实际上尝试从外部类中的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();
           }
       }
 }));
Run Code Online (Sandbox Code Playgroud)

Boo*_*Boo 6

为确保您的 ui 已刷新,您应该使用 Dispatcher

public static class UiRefresh
{

    private static Action EmptyDelegate = delegate () { };


    public static void Refresh(this UIElement uiElement)
    {
        uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
    }
}
Run Code Online (Sandbox Code Playgroud)

那么 yourElement.Refresh() 会起作用


Bel*_*ius 6

打电话((MainWindow)System.Windows.Application.Current.MainWindow).UpdateLayout()可以解决问题