RefreshItems
ViewModel のコンストラクターから呼び出され、ユーザーが希望するとき (RefreshCommand
ボタンのクリック時) に呼び出されます。
Delete も にバインドされDeleteCommand
ます。
他の方法では流動的ではないアニメーションがあるため、新しいスレッド内のアイテムを更新したいと思います。
したがって、バインディングはディスパッチャーのスレッドでは発生しませんが、削除は行われ、削除によって例外がスローされます (コードを参照)。
(XP をサポートする必要があるため、TPL (async/await) はオプションではありません。)
public void RefreshItems()
{
new Thread(new ThreadStart(() =>
{
IsRefreshing = true;
var items = _db.GetItems();
var itemsCollectionView = CollectionViewSource
.GetDefaultView(new ObservableCollection<ItemType>(items));
Items = itemsCollectionView;
IsRefreshing = false;
})).Start();
}
private void Delete(ItemType item)
{
_db.DeleteItem(item);
var items = (ObservableCollection<ItemType>)Items.SourceCollection;
// InnerException: NotSupportedException
// Message: This type of CollectionView does not support changes
// to its SourceCollection from a thread different from
// the Dispatcher thread.
items.Remove(item);
}