如果我的 ObservableCollection 在构造时未初始化,为什么我的 ObservableCollection 不会在更改时更新 UI?

Why does my ObservableCollection not update UI on change if it is not initialized at construction?

我已经解决这个问题好几个小时了,我不明白为什么会这样:

我的视图模型中有一个 ObservableCollection。使用以下代码一切正常:

class ExcelViewModel
{
  public ObservableCollection<EPCInformation> EPCEntries { get; set; }

  public ExcelViewModel()
  {
    EPCEntries = new ObservableCollection<EPCInformation>();
  }

  void AddEntry()
  {
    EPCEntries.Add(new EPCInformation
    {
      HexEPC = "TEST"
    });
  }
}

但是如果我在构建的时候不初始化EPCEntries,只是简单的设置为后面创建的ObservableCollection,我的UI不会更新:

class ExcelViewModel
{
  public ObservableCollection<EPCInformation> EPCEntries { get; set; }

  public ExcelViewModel()
  {
  }

  void AddEntry()
  {
    ObservableCollection<EPCInformation> tmp = new ObservableCollection<EPCInformation>();
    tmp.Add(new EPCInformation
    {
      HexEPC = "TEST"
    });
    EPCEntries = tmp;
  }
}

在这两种情况下单击按钮都会调用 AddEntry()

我是 WPF 和 C# 的新手,但我认为在第二种情况下会引发其他类型的事件,这就是 UI 不更新的原因。虽然想不通

我错过了什么?

您可以通过以下方式更改 class 以实现 INotifyPropertyChanged 以正确更新 UI。

public class ExcelViewModel : INotifyPropertyChanged
{
   //add private member and use RaisePropertyChanged in setter. 
   private ObservableCollection<EPCInformation> _epcEntries;
   public ObservableCollection<EPCInformation> EPCEntries 
   { 
         get {return _epcEntries;} 
         set
         {
            if (value == _epcEntries) return;
            _epcEntries = value;
            RaisePropertyChanged();
         }
   }

   public ExcelViewModel()
   {
     EPCEntries = new ObservableCollection<EPCInformation>();
   }

   void AddEntry()
   {
      EPCEntries.Add(new EPCInformation{HexEPC = "TEST"});
   }

   public event PropertyChangedEventHandler PropertyChanged;

   protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
   {
       PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
   }
}