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

时间:2019-06-20 13:48:04

标签: wpf mvvm observablecollection

这个问题已经存在了几个小时,我无法弄清楚为什么会发生这种情况:

我的视图模型中有一个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无法更新的原因。虽然我不知道。

我想念什么?

1 个答案:

答案 0 :(得分:1)

您可以在此处更改类,以实现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));
   }
}