我使用扩展的WPF工具包BusyIndicator
我的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之后显示BusyIndicator,
我试过了
wait.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send,
(Action)delegate
{
wait.IsBusy = true;
});但我什么都没拿到!我不能解决的问题在哪里?
我发现了一个类似的问题,但我没有同样的问题,指示器显示,但在函数完成后。
发布于 2011-07-17 02:05:02
问题是您在dispatcher的线程中执行所有工作(我假设esp_Click是一个事件处理程序)。这实际上意味着在执行长任务时,UI不会被更新。
您需要在单独的线程中执行工作-或者创建一个新线程,使用线程池或创建一个任务。在开始之前将IsBusy设置为true,在完成工作后将其设置为false。在从另一个线程更新wait.IsBusy时,您需要使用Dispatcher.BeginInvoke/Invoke。
示例代码:
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-09-06 04:34:25
您可以使用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);
}
}
}https://stackoverflow.com/questions/6718893
复制相似问题