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

前端 未结 3 541
傲寒
傲寒 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:13

    There is a big problem in your code. First, the ObservableCollection is already a collection that notifies on change, so you not need reinitialize it, just call Clear and Add/Insert.

    Second, the Employee class should be ViewModelBase:

    class Employee: ViewModelBase
    {
       private string _status;
    
       public string Name { get; set; }
       public string Status
       {
         get
         {
            return _status;
         }
         private set
         {
            _status=value;
           RaisePropertyChanged("Status");
         }
       }
    }
    

    This should allow you to change DailyEmployees[0].Status="NewStatus";

    LE: In case you have problems changing data from another thread, check this link: Using BindingOperations.EnableCollectionSynchronization

    LLE: I used the ViewModelBase class for the Employee, because it was already used in the code sample. A raw answer would have mean implementing the class Employee: INotifyPropertyChanged and implementing the required method.

提交回复
热议问题