WPF动态创建页面时显示忙碌指示符的最佳方式

时间:2013-03-11 20:39:43

标签: wpf xbap busyindicator

我有一个WPF应用程序,它在浏览器中作为XBAP运行。在几个页面上,所有控件都是根据用户选择的内容动态创建的。因此,在加载所有控件之前,应用程序看起来似乎没有做任何事情。我想先显示一些繁忙的指示器,向用户显示控件正在加载,它不需要动画,但如果它确实会很好。我已经查看了telerik忙指示符,但这不起作用,因为它实际上是为单个控件获取数据,并且直到控件加载时才会显示,这会失败。

我正在考虑首先显示包含加载徽标的叠加层或类似内容,然后在页面后面加载页面并在加载控件时隐藏叠加层。我想知道这是否是解决这个问题的最佳方式,还是有更好的方法?

1 个答案:

答案 0 :(得分:2)

注意:我没有在XBAP浏览器应用程序中尝试过这个,但它在WPF应用程序中运行没有任何问题! 我使用DispatcherTimer在必要时显示沙漏,并将此代码抽象为静态类。

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();
        }
    }
}

您可以这样使用它:

void DoSomething()
{
    UiServices.SetBusyState();
    // Do your thing
}

希望这有帮助!

相关问题