加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 从另一个线程更新ObservableCollection

发布时间:2020-12-15 08:21:16 所属栏目:百科 来源:网络整理
导读:我一直在尝试处理Rx库并使用MVVM在 WPF中进行处理.我将我的应用程序分解为诸如存储库和ViewModel之类的组件.我的存储库能够一个接一个地提供学生集合,但是当我尝试添加到View绑定的ObservableCollection时,它会抛出一个线程错误.我会指出一些指针,让这对我有
我一直在尝试处理Rx库并使用MVVM在 WPF中进行处理.我将我的应用程序分解为诸如存储库和ViewModel之类的组件.我的存储库能够一个接一个地提供学生集合,但是当我尝试添加到View绑定的ObservableCollection时,它会抛出一个线程错误.我会指出一些指针,让这对我有用.

解决方法

您需要使用正确设置同步上下文
ObserveOn(SynchronizationContext.Current)

看到这篇博文

http://10rem.net/blog/2011/02/17/asynchronous-web-and-network-calls-on-the-client-in-wpf-and-silverlight-and-net-in-general

举个例子.

这是一个适合我的例子:

<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; }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读