How to update only a property in an observable collection from thread other than dispatcher thread in WPF MVVM?

前端 未结 3 503
傲寒
傲寒 2021-01-24 12:30

I am having a class named Employee. I need to update only the property Status from thread other than current dispatcher thread:

         


        
3条回答
  •  太阳男子
    2021-01-24 13:01

    Either use the dispatcher to call the Add method on the UI thread:

    Application.Current.Dispatcher.BeginInvoke(() => DailyEmployees.Add(em)); 
    

    Or call the BindingOperations.EnableCollectionSynchronization method on the UI thread to enable the collection to be used on multiple threads:

    public class DisplayViewModel
    {
        private readonly ObservableCollection _dailyEmployees = new ObservableCollection();
        private readonly object _lock = new object();
    
        public ObservableCollection DailyEmployees
        {
            get { return _dailyEmployees; }
        }
    
        public DisplayViewModel()
        {
            System.Windows.Data.BindingOperations.EnableCollectionSynchronization(_dailyEmployees, _lock);
            OnStatusChanged += DisplayViewModel_OnStatusChanged;
        }
    
        //invoked in other thread
        private void DisplayViewModel_OnStatusChanged(object sender, EventArgs e)
        {
            var d = sender as Employee;
            if (d == null)
                return;
            var em = DailyEmployees.FirstOrDefault(a => a.Name == d.Name);
    
            if (em == null)
            {
                DailyEmployees.Add(em);
            }
            else
            {
                em.Status = d.Status;
            }
        }
    }
    

    Also note that the Employee class should implement the INotifyPropertyChanged interface and raise the PropertyChanged event for the Status property if you want the value of this one to be reflected in the view when you set it.

提交回复
热议问题