[英]How to show the wait cursor in UI while backgroud thread running
單擊按鈕打開下一個窗口時,我需要顯示等待光標。 在我的應用程序中單擊按鈕加載背景中下一個窗口的值。 打開下一個窗口需要一些時間。 在此期間,我想在 UI 中顯示等待光標。 所以我使用了下面的代碼,但它在后台進程完成后顯示等待光標。
請任何人分享您的建議如何在后台線程運行時顯示等待光標?
private void Button_Click(object sender, RoutedEventArgs e)
{
System.Threading.Thread thread = new System.Threading.Thread(() =>
{
this.Dispatcher.Invoke((Action)(() =>
{
this.Cursor= Cursors.Wait;
}));
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = false;
thread.Start();
System.Threading.Thread.Sleep(3000);
}
如果用戶無論如何都必須等待,為什么要使用后台線程來加載窗口?
可以這樣做:
private async void Button_Click(object sender, RoutedEventArgs e)
{
try
{
Mouse.OverrideCursor = Cursors.Wait;
await Task.Run(() => LoadWindow());
}
finally
{
Mouse.OverrideCursor = null;
}
}
但隨后 UI 保持響應- 這與您使用等待光標相矛盾。
我認為最好沒有后台線程,只需在打開窗口之前設置光標,然后再將其放回原處。
我為此使用了一些助手:
internal static void ShowWithWaitCursor(this Window view)
{
WithWaitCursor(() => view.Show());
}
internal static void WithWaitCursor(Action action)
{
Func<int> func = () => { action.Invoke(); return 0; };
WithWaitCursor<int>(func);
}
internal static T WithWaitCursor<T>(Func<T> func)
{
try
{
Mouse.OverrideCursor = Cursors.Wait;
return func.Invoke();
}
finally
{
Mouse.OverrideCursor = null;
}
}
打開一個窗口:
Window win = new MyWindow();
win.DataContext = new MyViewModel(injectDependencies);
win.ShowWithWaitCursor();
有時 ViewModel 也需要一些時間來加載,所以我使用這個:
Window win = new MyWindow();
win.DataContext = WindowHelpers.WithWaitCursor(() => new MyViewModel(injectDependencies));
win.ShowWithWaitCursor();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.