你需要做的是使用MVVM。
将您的控件绑定到ViewModel上的公共属性。您的虚拟机可以侦听串行端口,解析出xml数据,更新其公共属性,然后使用INotifyPropertyChanged来通知UI更新其绑定。
我会建议这条路线,因为你可以批量通知,如果你必须使用分派器来调用UI线程上的事件。
UI:
<Window ...>
<Window.DataContext>
<me:SerialWindowViewModel />
</Window.DataContext>
<Grid>
<TextBlock Text="{Binding LatestXml}/>
</Grid>
</Window>
SerialWindowViewModel:
public class SerialWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string LatestXml {get;set;}
private SerialWatcher _serialWatcher;
public SerialWindowViewModel()
{
_serialWatcher = new SerialWatcher();
_serialWatcher.Incoming += IncomingData;
}
private void IncomingData(object sender, DataEventArgs args)
{
LatestXml = args.Data;
OnPropertyChanged(new PropertyChangedEventArgs("LatestXml"));
}
OnPropertyChanged(PropertyChangedEventArgs args)
{
// tired of writing code; make this threadsafe and
// ensure it fires on the UI thread or that it doesn't matter
PropertyChanged(this, args);
}
}
而且,如果这是不能接受的,你(和你要喜欢它的一个WinForms应用程序编程WPF),您可以使用调度。 CurrentDispatcher在您手动更新表单上的所有控件时调用一次。但是那个方法太臭了。
谢谢!这看起来像我可以实现的东西! – Klay 2009-07-10 19:11:27