等待光标直到UI准备就绪。如何?

时间:2015-03-23 19:01:17

标签: wpf

我有一个包含数百个复杂元素的ListView。当绑定到ListView的集合已经填充了数据时,它需要几秒钟,直到UI变得响应。收集完成后,我的等待光标会变回常规,但我希望它等待UI响应。我不确定后台发生了什么,但我猜WPF元素已初始化。是否有一个事件我可以等待WPF完成更新?

(只要显示等待光标,用户就可以等待。)

1 个答案:

答案 0 :(得分:1)

在项目中创建一个新类,调用它的UIServices是代码

/// <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, System.Windows.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();
        }
    }
}

然后您可以在viewmodel或后面的代码中使用它,如下所示:

 UIServices.SetBusyState();

这将为用户提供等待光标,直到您的应用程序忙碌