我正在为 Windows 8 编写一个 Windows Store App 玩具应用程序。
它只有一个 xaml 页面,其中包含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);
}
with
private void NotifyTimeChanged(){
if (this.PropertyChanged != null){
this.PropertyChanged(this, new PropertyChangedEventArgs("Time"));
}
}
the 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 本身,
我无法弄清楚,但我认为解决方案应该使用类似的东西this one https://stackoverflow.com/questions/6268250/begininvoke-gui-and-thread.