XMAL中添加ProgresBar控件:
<ProgressBar Height="60" HorizontalAlignment="Left" Margin="8,167,0,0" Name="pb_import" VerticalAlignment="Top" Width="600" />
接下来是后台的代码,先是函数外的代理预定义,接下来就是内部的代理声明,接着调用for循环中的函数就行了,我的代码是for循环获取网络回复然后更新进度条(progressbar)
cs文件中代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.SetValue(1000);
}
private void SetValue(int count)
{
for (int i = 0; i < count; i++)
{
beginImport(i);
}
}
private delegate void UpdateProgressBarDelegate(System.Windows.DependencyProperty dp, Object value);
private void beginImport(int i)
{
pb_import.Maximum = 1000;
pb_import.Value = 0;
UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(pb_import.SetValue);
Thread thread = new Thread(new ThreadStart(() =>
{
Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(i + 1) });
Thread.Sleep(100);
}));
thread.Start();
}
}
}