显示与QUOT;等待"屏幕在WPF屏幕、QUOT、WPF

2023-09-02 21:51:27 作者:千寻.

我想显示一个长期运行的操作请稍候对话框。现在的问题是,因为这是即使我告诉等待屏幕来显示它从来不会单线程的。有没有一种方法,我可以改变屏幕的可见性,并使其立即显示?我包括光标呼叫作为一个例子。我叫this.Cursor权后,光标立即更新。这正是我想要的行为。

I am trying to display a please wait dialog for a long running operation. The problem is since this is single threaded even though I tell the WaitScreen to display it never does. Is there a way I can change the visibility of that screen and make it display immediately? I included the Cursor call as an example. Right after I call this.Cursor, the cursor is updated immediately. This is exactly the behavior I want.

private void Button_Click(object sender, RoutedEventArgs e)
{
  this.Cursor = System.Windows.Input.Cursors.Pen;
  WaitScreen.Visibility = Visibility.Visible;

  // Do something long here
  for (Int32 i = 0; i < 100000000; i++)
  {
    String s = i.ToString();
  }

  WaitScreen.Visibility = Visibility.Collapsed;
  this.Cursor = System.Windows.Input.Cursors.Arrow; 
}

等待屏幕仅仅是一个99,我隐藏和显示一个Z型指数网格。

WaitScreen is just a Grid with a Z-index of 99 that I hide and show.

更新:我真的不希望使用一个后台工作,除非我不得不这样做。有许多在code地方这个启动和停止将发生

update: I really don't want to use a background worker unless I have to. There are a number of places in the code where this start and stop will occur.

推荐答案

我找到了一种方法!感谢this螺纹。

I found a way! Thanks to this thread.

public static void ForceUIToUpdate()
{
  DispatcherFrame frame = new DispatcherFrame();

  Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Render, new DispatcherOperationCallback(delegate(object parameter)
  {
    frame.Continue = false;
    return null;
  }), null);

  Dispatcher.PushFrame(frame);
}

这功能需要长时间运行的操作之前,有权被调用。这将迫使UI线程更新。

That function needs to be called right before the long running operation. That will then Force the UI thread to update.