Ars*_*han 6 c# wpf system.reactive
我一直在尝试处理Rx库并使用MVVM在WPF中进行处理.我将我的应用程序分解为诸如存储库和ViewModel之类的组件.我的存储库能够一个接一个地提供学生集合,但是当我尝试添加到View绑定的ObservableCollection时,它会抛出一个线程错误.我会指出一些指针,让这对我有用.
您需要使用正确设置同步上下文
ObserveOn(SynchronizationContext.Current)
Run Code Online (Sandbox Code Playgroud)
看到这篇博文
举个例子.
这是一个适合我的例子:
<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; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6776 次 |
| 最近记录: |