现在的位置: 首页 > 综合 > 正文

在WPF 中使用 BackgroundWorker

2013年02月28日 ⁄ 综合 ⁄ 共 1536字 ⁄ 字号 评论关闭

1. MainWindow.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>
        <Label Content="Label" Height="28" HorizontalAlignment="Left" Margin="123,100,0,0" Background="Yellow" Name="label1" VerticalAlignment="Top" Width="91" />
    </Grid>
</Window>

2. MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Threading;

namespace WpfApplication3
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        BackgroundWorker bw = new BackgroundWorker();
        public MainWindow()
        {
            InitializeComponent();
            bw.WorkerReportsProgress = true; 
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerAsync();           
        }      

        void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage % 2 == 0)
            {
                this.label1.Background = Brushes.Blue;
            }
            else
            {
                this.label1.Background = Brushes.Yellow;
            }
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;           
            int iCount = new Random().Next(20, 50);
            for (int i = 0; i < iCount; i++)
            {                
                worker.ReportProgress(i);
                Thread.Sleep(200);               
            }
        }
    }
}

【上篇】
【下篇】

抱歉!评论已关闭.