WPF使用多线程访问控件及打开新窗口:
private void button1_Click(object sender, RoutedEventArgs e)
{
Thread thread = new Thread(new ParameterizedThreadStart(AppendData));
thread.SetApartmentState(ApartmentState.STA);//由新线程去开启新窗口时需要设置
thread.IsBackground = true;
thread.Start("ABC");
}
delegate void AppendText(string message);
void AppendData(object msge)
{
Dispatcher.BeginInvoke(new AppendText(app), new object[] { msge.ToString() });//访问控件
Th t = new Th();
t.Show();
System.Windows.Threading.Dispatcher.Run();//开启新窗口后要是没有加上这句,打开的窗口会很快被关闭掉
}
//控件赋值
void app(string msg)
{
txtbox.Text = msg;
}
WPF实现与winform的timer控件功能
使用
DispatcherTimer 类
DispatcherTimer timer = null;
public MainWindow()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = TimeSpan.FromSeconds(1);
timer.Start();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
timer.Stop();//停止
}