您的位置:首页 > 其它

wpf中使用线程的问题

2013-12-24 18:11 330 查看
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模式,把控件属性绑定到类,代码会更“干净”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐