2009-07-08 48 views
2

我正在使用SerialPort类中的事件侦听器从串行端口读取数据。在我的事件处理程序中,我需要使用通过串行端口传递的xml数据更新窗口中的许多(30-40)控件。wpf:通过调度程序更新多个控件

我知道,我必须用myControl.Dispatcher.Invoke()来因为它是在不同的线程,但有没有办法来更新大量的控制一起,而不是做一个单独的invoke调用每个更新(即myCon1.Dispatcher.Invoke(),myCon2.Dispatcher.Invoke()等)?

我正在寻找类似调用容器上的Invoke,并单独更新每个子控件,但我似乎无法解决如何实现这一点。

谢谢!

回答

1

你需要做的是使用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在您手动更新表单上的所有控件时调用一次。但是那个方法太臭了。

+0

谢谢!这看起来像我可以实现的东西! – Klay 2009-07-10 19:11:27