wpf中使用线程的问题

http://social.msdn.microsoft.com/Forums/zh-CN/504fa86b-7d2d-4424-8f6f-ac9b3a9d480e/wpf



xaml:
    <StackPanel Orientation="Vertical">
        <TextBox Name="textBox1" Text="20"/>
        <TextBlock Name="textBlock1"/>
        <Button Content="Button" Click="button1_Click" />
    </StackPanel>
后台:
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            using (BackgroundWorker bw = new BackgroundWorker())
            {
                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                bw.RunWorkerAsync();
            }
        }
        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            textBlock1.Text = "completed";
        }
        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            int times = 0;
            Dispatcher.Invoke(new Action(delegate()
            {
                times = Convert.ToInt32(textBox1.Text);
            }));
            for (int i = 0; i < times; i++)
            {
                Dispatcher.BeginInvoke(new Action(delegate()
                {
                    textBlock1.Text = string.Format("current i:{0}", i);
                }));
                Thread.Sleep(new TimeSpan(0, 0, 1));
            }
        }
    }
这应该符合你的情况了,后台线程中要获得控件属性,并修改控件属性。建议用MVVM模式,把控件属性绑定到类,代码会更“干净”。


你可能感兴趣的:(wpf中使用线程的问题)