我正在为 Windows 8 编写一个 Windows Store App 玩具应用程序。它只有一个带有TextBlock
. 该页面的 MyTimer 类为DataContext
:
this.DataContext = new MyTimer();
MyTimer
实现并使用计时器INotifyPropertyChanged
更新属性:Time
public MyTimer(){
TimerElapsedHandler f = new TimerElapsedHandler(NotifyTimeChanged);
TimeSpan period = new TimeSpan(0, 0, 1);
ThreadPoolTimer.CreatePeriodicTimer(f, period);
}
和
private void NotifyTimeChanged(){
if (this.PropertyChanged != null){
this.PropertyChanged(this, new PropertyChangedEventArgs("Time"));
}
}
在TextBlock
时间上有一个数据绑定
<TextBlock Text="{Binding Time}" />
当我运行应用程序时,出现以下异常:
System.Runtime.InteropServices.COMException was unhandled by user code
随着消息
The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
真正的问题是我正在更新类 MyTimer 的属性,而不是 GUI 本身,我无法弄清楚,但我认为解决方案应该使用类似这样的东西。