gpt4 book ai didi

wpf - 当 WPF 应用程序正忙于数据绑定(bind)时如何显示等待光标

转载 作者:行者123 更新时间:2023-12-02 20:32:55 25 4
gpt4 key购买 nike

我有一个使用 MVVM 模式的 WPF 应用程序,当它忙于执行用户必须等待的操作时,有时必须显示等待光标。感谢本页上的答案组合:display Hourglass when application is busy ,我有一个几乎可以工作的解决方案(尽管它在精神上并不是真正的 MVVM)。每当我在 View 模型中做一些耗时的事情时,我都会这样做:

using (UiServices.ShowWaitCursor())
{
.. do time-consuming logic
this.SomeData = somedata;
}

(ShowWaitCursor() 返回一个 IDisposable,该 IDisposable 会显示 waitcursor,直到它被释放为止)我的示例中的最后一行是我设置一些属性的地方。此属性绑定(bind)在我的 XAML 中,例如像这样:

<ItemsControl ItemsSource="{Binding SomeData}" /> 

但是,由于这可能是一长串对象,有时还包含复杂的数据模板等,因此实际的绑定(bind)和渲染有时需要相当长的时间。由于此绑定(bind)发生在我的 using 语句之外,因此等待光标将在用户的实际等待结束之前消失。

所以我的问题是如何在考虑数据绑定(bind)的 WPF MVVM 应用程序中执行等待光标?

最佳答案

Isak 的答案对我来说不起作用,因为它没有解决用户实际等待结束时如何操作的问题。我最终这样做了:每次我开始做一些耗时的事情时,我都会调用一个辅助方法。此辅助方法会更改光标,然后创建一个 DispatcherTimer,当应用程序空闲时将调用该 DispatcherTimer。当它被调用时,它将鼠标光标设置回来:

/// <summary>
/// Contains helper methods for UI, so far just one for showing a waitcursor
/// </summary>
public static class UiServices
{

/// <summary>
/// A value indicating whether the UI is currently busy
/// </summary>
private static bool IsBusy;

/// <summary>
/// Sets the busystate as busy.
/// </summary>
public static void SetBusyState()
{
SetBusyState(true);
}

/// <summary>
/// Sets the busystate to busy or not busy.
/// </summary>
/// <param name="busy">if set to <c>true</c> the application is now busy.</param>
private static void SetBusyState(bool busy)
{
if (busy != IsBusy)
{
IsBusy = busy;
Mouse.OverrideCursor = busy ? Cursors.Wait : null;

if (IsBusy)
{
new DispatcherTimer(TimeSpan.FromSeconds(0), DispatcherPriority.ApplicationIdle, dispatcherTimer_Tick, Application.Current.Dispatcher);
}
}
}

/// <summary>
/// Handles the Tick event of the dispatcherTimer control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private static void dispatcherTimer_Tick(object sender, EventArgs e)
{
var dispatcherTimer = sender as DispatcherTimer;
if (dispatcherTimer != null)
{
SetBusyState(false);
dispatcherTimer.Stop();
}
}
}

关于wpf - 当 WPF 应用程序正忙于数据绑定(bind)时如何显示等待光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7346663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com