【问题标题】:WPF Best way of displaying a busy indicator when dynamically creating a pageWPF 动态创建页面时显示繁忙指示器的最佳方式
【发布时间】:2013-02-27 04:42:31
【问题描述】:

我有一个在浏览器中作为 XBAP 运行的 WPF 应用程序。在几个页面上,所有控件都是根据用户选择的内容动态创建的。因此,在加载所有控件之前,应用程序可能看起来没有做任何事情。我想事先显示某种繁忙的指示器,以向用户显示控件正在加载,它不必动画,但如果这样做会很好。我查看了telerik忙指示器,但这不起作用,因为它实际上是为了获取单个控件的数据,并且在加载控件之前不显示,这违背了目的。

我正在考虑显示一个覆盖或类似的东西,首先包含一个加载徽标,然后加载其后面的页面并在控件加载时隐藏覆盖。我想知道这是否是解决此问题的最佳方法,或者是否有更好的方法?

【问题讨论】:

  • 没有更好的方法,因为所有 UI 操作都需要在 UI 线程中进行。不过,我很担心你的声明On a few pages all the controls are dynamically created depending on what the user selects。听起来您没有应用正确的模式 (MVVM) 并且正在代码中创建所有这些 UI 元素,这很糟糕,并且可能导致所有这些性能问题。显示一些代码,也许我们可以帮助你。
  • 不幸的是,我不允许发布代码,但基本上一个页面可以包含大量文本框、列表框、下拉列表、用户控件等,用户可以选择在页面上显示或隐藏,具体取决于他们需要什么,所以它是高度可定制的。这些控件的加载可能需要一些时间。它是 MVVM,但我继承了代码,所以也许还有其他事情可以做。无论如何,干杯必须看看那个和覆盖。
  • @knappster 就像 HighCode 所说的,应该不需要“加载”自定义控件。有一些技术可以实现这一点。您可以使用 DataTriggers 根据属性值显示/隐藏某些控件,您可以将控件集抽象为 UserControls 并使用 DataTemplate(任何 DataTemplateSelector)来控制使用哪个 UserControl。无论如何,我会尝试为您的实际问题提供答案(下面的鼠标沙漏)

标签: wpf xbap busyindicator


【解决方案1】:

注意:我没有在 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
}

希望这会有所帮助!

【讨论】:

  • 干杯,我会在 XBAP 浏览器中试一试,看看它是否有效。
猜你喜欢
  • 2015-07-31
  • 1970-01-01
  • 2013-01-23
  • 2012-05-28
  • 2012-03-28
  • 1970-01-01
  • 2011-04-08
  • 1970-01-01
  • 2012-09-28
相关资源
最近更新 更多