对ObservableCollection中更改的对象进行了反应

时间:2013-11-05 18:54:04

标签: c# wpf mvvm

我的viewmodel中有一个ObservableCollection<Person>。这被绑定为ItemsSource到视图中的DataGrid。 Person类只有三个属性:

 public class Person : ViewModelBase
    {
        private Guid id;
        public Guid Id
        {
            get { return this.id; }
            set
            {
                this.id = value;
                OnPropertyChanged("Id");
            }
        }

        private string firstname;
        public string Firstname
        {
            get { return this.firstname; }
            set
            {
                this.firstname = value;
                OnPropertyChanged("Firstname");
            }
        }

        private string lastname;
        public string Lastname
        {
            get { return this.lastname; }
            set
            {
                this.lastname = value;
                OnPropertyChanged("Lastname");
            }
        }
    }

ViewModelBase类实现了INotifyPropertyChanged。

如果我在dategrid中添加或删除条目,则集合中的项目将更新完美。然后该项目也将在集合中删除。

我的问题是人物项目的内容已更新,但我不知道如何对此做出反应。

我是否必须向某个人类添加一个事件或其他内容以获取信息,或者是否有其他方法可以执行此操作?

1 个答案:

答案 0 :(得分:3)

在类Person上实现INotifyPropertyChanged接口,以便Person属性中的任何更改都会反映在UI上。

样本 -

public class Person : INotifyPropertyChanged
{
   private Guid id;
   public Guid Id
   {
      get { return id; }
      private set
      {
         if(id != value)
         {
            id = value;
            NotifyPropertyChanged("Id");
         }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string propertyName)
    {
       if (PropertyChanged != null)
       {
          PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
       }
    }
}