WPF中进度条控件在后台控制进度

 

XAML代码:

<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">

<Grid >
<ProgressBar x:Name="ProgressBar" Margin="10"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Height="23" ></ProgressBar>
</Grid>

</Window>

c#代码:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainWindow_Loaded);
}

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{ //BackgroundWorker,在单独的线程上执行操作
BackgroundWorker worker = new BackgroundWorker();

//BW.DoWork,调用BW.RunWorkerAsync()时发生

//初始化命名委托;Lambda 运算符的左边是输入参数(如果有),右边包含表达式或语句块;
worker.DoWork += (s,ev) =>
{
for (int i = 0; i < 100; i += 10)
{
Thread.Sleep(1000);

//BW.ReportProgress,引发BW.ProgressChanged事件
((BackgroundWorker)s).ReportProgress(i);
}
};
//调用BW.ReportProgress时发生
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);

//当后台操作已完成,被取消或引发异常时发生
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

//BackgroundWorker.WorkerReportsProgress 获取或设置一个值,该值指示 BackgroundWorker 能否报告进度更新。
worker.WorkerReportsProgress = true;

//TaskbarItemInfo获取或设置 System.Windows.Window 的任务栏缩略图。
//TaskbarItemInfo.ProgressState 获取或设置一个值,该值指示在任务栏按钮中显示进度指示器的方式。

//TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Indeterminate;

//TaskbarItemProgressState枚举值
//None=0,Indeterminate=1(闪烁绿色),Normal=2(绿色),Error=3(红色),Paused=4(黄色)
//开始执行后台操作
worker.RunWorkerAsync();

}


void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//ProgressChangedEventArgs.ProgressPercentage 获取异步任务的进度百分比
ProgressBar.Value = e.ProgressPercentage;

// double TaskbarItemInfo.ProgressValue获取或设置一个值,该值指示任务栏按钮中进度指示器的填满状态。
//TaskbarItemInfo.ProgressValue = (double)e.ProgressPercentage / 100;
}

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
ProgressBar.Value = 100;
MessageBox.Show("操作完成");
//TaskbarItemInfo.ProgressValue = 1.0;
}
}

posted @ 2012-04-10 21:05  @张凯@  阅读(3864)  评论(0编辑  收藏  举报