[英]Updating an ObservableCollection from another thread
我一直在嘗試處理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; }
}
你的代碼是在后台線程上運行的嗎? 由於它會影響UI,因此只能在UI / Dispatcher線程上更新View綁定的ObservableCollection。
有關類似問題,請參閱WPF ObservableCollection線程安全性 。
對UI的任何更改都應由Dispatcher
線程完成。 如果你有一個不斷更改視圖模型的anthoer線程的好習慣是強制屬性設置器使用調度程序線程。 在這種情況下,您確保不會更改另一個線程上的UI元素。
嘗試:
public string Property
{
set
{
Dispatcher.BeginInvoke(()=> _property = value ) ;
OnPropertyChanged("Property");
}
get
{
return _property;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.