实现实时更新ProgressBar貌似有很多方法,我搜索的很多资料都要用线程,觉得还是有点儿麻烦,最后在国外的技术论坛上看到一个用代理解决的方法,下面就是我的调试过程:
1. 先来看ProgressBar的代码
<ProgressBar Height="20" HorizontalAlignment="Left" Margin="8,167,0,0" Name="pb_import" VerticalAlignment="Top" Width="243" />
2. 接下来是后台的代码,先是函数外的代理预定义,接下来就是内部的代理声明,接着调用for循环中的函数就行了,我的代码是for循环获取网络回复然后更新进度条(progressbar),除progessbar相关的代码被删除了,你可以自由组装下面的代码。
private delegate void UpdateProgressBarDelegate(System.Windows.DependencyProperty dp, Object value); private void beginImport() { pb_import.Maximum = 100; pb_import.Value = 0; UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(pb_import.SetValue); for (int i = 0; i < 100; i++) { Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty,Convert.ToDouble( i + 1) }); } }
3. 至于会用到的命名空间,你自己看着办吧,别太省事了。