3

我使用扩展的 WPF 工具包 BusyIndi​​cator

我的 Xaml

<extToolkit:BusyIndicator Name="wait" IsBusy="False" Cursor="Wait" Grid.ColumnSpan="3" Margin="10,10,10,10"/>

我的代码:

private void esp_Click(object sender, RoutedEventArgs e)
{
    wait.IsBusy = true;

    // My work here make some time to finish

    wait.IsBusy = false;
}

但它永远不会显示,我尝试在函数的末尾让 MessageBox 在 MessageBox 之后显示 BusyIndi​​cator,

我试过

wait.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                       (Action)delegate
{
    wait.IsBusy = true;
});

但是我什么都没有!!!我无法解决的问题在哪里?

我发现了一个类似的问题,但我没有同样的问题,但在功能完成后,指示器出现了。

4

2 回答 2

6

问题是您正在调度程序的线程中执行所有工作(我假设这esp_Click是一个事件处理程序)。这实际上意味着在执行长任务时,UI 不会被更新。

您需要在单独的线程中执行工作 - 创建一个新线程、使用线程池或创建一个任务。在开始之前和完成工作之后设置IsBusy为。从另一个线程更新时需要使用。truefalseDispatcher.BeginInvoke/Invokewait.IsBusy

示例代码:

private void LongRunningTask() 
{
   // your long running code

   // after you complete:
   Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
                           (Action)delegate
    {
        wait.IsBusy = false;
    }); 
}

private void esp_Click(object sender, RoutedEventArgs e)
{
   wait.IsBusy = true; // either here, or in your long running task - but then remember to use dispatcher

   var thread = new Thread(LongRunningTask);
   thread.Start();

   // OR

   ThreadPool.QueueUserWorkItem(state => LongRunningState());

   // OR, in .NET 4.0

   Task.Factory.StartNew(LongRunningTask);
}

请注意,这两种解决方案都不能处理异常 - 您必须自己添加错误处理(或在最后一个示例的情况下使用任务延续)。

于 2011-07-16T18:05:01.737 回答
2

你可以这样做INotifyPropertyChanged

<extToolkit:BusyIndicator Name="wait" IsBusy="{Binding IsBusy}" Cursor="Wait" Grid.ColumnSpan="3" Margin="10,10,10,10"/>

和 C#:

    /// <summary>
    /// The <see cref="IsBusy" /> property's name.
    /// </summary>
    public const string IsBusyPropertyName = "IsBusy";
    private bool _isBusy = false;

    public bool IsBusy
    {
        get
        {
            return _isBusy;
        }

        set
        {
            if (_isBusy != value)
            {
                _isBusy = value;
                RaisePropertyChanged(IsBusyPropertyName);                   
            }
        }
    }
于 2011-09-05T20:34:25.430 回答