我一直在尝试处理Rx库并使用MVVM在
WPF中进行处理.我将我的应用程序分解为诸如存储库和viewmodel之类的组件.我的存储库能够一个接一个地提供学生集合,但是当我尝试添加到View绑定的ObservableCollection时,它会抛出一个线程错误.我会指出一些指针,让这对我有用.
解决方法
您需要使用正确设置同步上下文
ObserveOn(SynchronizationContext.Current)
看到这篇博文
举个例子.
这是一个适合我的例子:
<Page.Resources> <viewmodel:ReactiveListviewmodel x:Key="model"/> </Page.Resources> <Grid DataContext="{StaticResource model}"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <Button Content="Start" Command="{Binding StartCommand}"/> <ListBox ItemsSource="{Binding Items}" Grid.Row="1"/> </Grid> public class ReactiveListviewmodel : viewmodelBase { public ReactiveListviewmodel() { Items = new ObservableCollection<long>(); StartCommand = new RelayCommand(Start); } public ICommand StartCommand { get; private set; } private void Start() { var observable = Observable.Interval(TimeSpan.FromSeconds(1)); //Exception: This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread. //observable.Subscribe(num => Items.Add(num)); // Works fine observable.ObserveOn(SynchronizationContext.Current).Subscribe(num => Items.Add(num)); // Works fine //observable.ObserveOnDispatcher().Subscribe(num => Items.Add(num)); } public ObservableCollection<long> Items { get; private set; } }