Update an ObservableCollection with a background worker in MVVM

后端 未结 3 669
谎友^
谎友^ 2020-12-10 14:13

Ok, I recently implemented a background worker to perform saving and loading of data.

However, getting this to work on a save command has proved difficult.

B

3条回答
  •  悲哀的现实
    2020-12-10 14:53

    I found a blog post that uses the Dispatcher to manage all of the ObeservableCollection's methods. Here is a snip-it of the code, see the post for the entire class.

    public class DispatchingObservableCollection : ObservableCollection
    {
        /// 
        /// The default constructor of the ObservableCollection
        /// 
        public DispatchingObservableCollection()
        {
            //Assign the current Dispatcher (owner of the collection)
            _currentDispatcher = Dispatcher.CurrentDispatcher;
        }
    
        private readonly Dispatcher _currentDispatcher;
    
        /// 
        /// Executes this action in the right thread
        /// 
        ///The action which should be executed
        private void DoDispatchedAction(Action action)
        {
            if (_currentDispatcher.CheckAccess())
                action();
            else
                _currentDispatcher.Invoke(DispatcherPriority.DataBind, action);
        }
    
        /// 
        /// Clears all items
        /// 
        protected override void ClearItems()
        {
            DoDispatchedAction(() => base.ClearItems());
        }
    
        /// 
        /// Inserts a item at the specified index
        /// 
        ///The index where the item should be inserted
        ///The item which should be inserted
        protected override void InsertItem(int index, T item)
        {
            DoDispatchedAction(() => base.InsertItem(index, item));
        }
    

提交回复
热议问题