Listbox bound to an ObservableCollection doesn't update

后端 未结 3 1129
难免孤独
难免孤独 2020-12-21 07:36

I am using a ObservableCollection to store the Environment Variables of Windows.

class VariableVieWModel
{
    ObservableCollection vars         


        
相关标签:
3条回答
  • 2020-12-21 08:00

    You need to implement INotifyPropertyChanged for your VariableVieWModel to refresh your target object bindings. You just have to do this way -

    class VariableVieWModel : INotifyPropertyChanged
        { .
          .
                public ObservableCollection<VariableModel> Variables
                {
                   get
                   {
                      return vars;
                   }
                   set
                   {
                      if(vars!=value)
                      {
                          vars = value;
                          OnPropertyChanged("Variables");
                      }
                   }
                }
    
                public event PropertyChangedEventHandler PropertyChanged;      
                protected void OnPropertyChanged(string name)
                {
                    PropertyChangedEventHandler handler = PropertyChanged;
                    if (handler != null)
                    {
                        handler(this, new PropertyChangedEventArgs(name));
                    }
                } 
        }
    
    0 讨论(0)
  • 2020-12-21 08:07

    You haven't modified the ObservableCollection, only replaced it. You should implement INotifyPropertyChanged and call PropertyChanged in the Variables property setter.

    BTW it's common in MVVM implementations to have a base class for your ViewModel:

    class VariableViewModel : ViewModelBase
    

    and implement common functionality such as INotifyPropertyChanged in the base class to avoid duplication of code.

    0 讨论(0)
  • 2020-12-21 08:13

    The problem is, that probably your VariableModel does not implement INotifyPropertyChanged. Through ObservableCollection, only changes to the collection are reported, not changes of the contained objects.

    Here you will find some implementation possibilities.

    0 讨论(0)
提交回复
热议问题