INotifyPropertyChange〜没有的PropertyChanged射击练习时属性是一个集合和一个新的项目添加到集合 [英] INotifyPropertyChange ~ PropertyChanged not firing when property is a collection and a new item is added to the collection

查看:159
本文介绍了INotifyPropertyChange〜没有的PropertyChanged射击练习时属性是一个集合和一个新的项目添加到集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现INotifyPropertyChanged接口的类。一些类的属性是列表类型。例如:

I have a class that implements the INotifyPropertyChanged interface. Some of the properties of the class are of type List. For example:

public List<string> Answers
{
    get { return _answers;  }
    set
    {
      _answers = value;
      onPropertyChanged("Answers")
    }
}

...

private void onPropertyChanged(string propertyName)
{
    if(this.PropertyChanged != null)
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

如果我分配一个新的List<串GT;到答案,那么PropertyChanged事件触发的预期;但如果我使用列表添加方法添加一个字符串,字符串的答案列表,然后PropertyChanged事件不火。

If I assign a new List<string> to Answer, then the PropertyChanged event fires as expected; but if I add a string string to the Answer list using the List Add method, then PropertyChanged event doesn't fire.

我正在考虑增加一个AddAnswer()方法我的类,它会处理调用列表的添加方法,并称之为onPropertyChanged()从那里,但就是正确的方式做到这一点?是否有这样做的更优雅的方式?

I was considering adding an AddAnswer() method to my class, which would handle calling the lists's Add method and would call onPropertyChanged() from there, but is that the right way to do it? Is there a more elegant way of doing it?

干杯,
KT

Cheers, KT

推荐答案

您应该暴露一个 的ObservableCollection<串GT; ,它实现了 INotifyCollectionChange 接口,以提高自身的变化事件。

You should expose an ObservableCollection<string>, which implements the INotifyCollectionChange interface to raise its own change events.

您还应该删除属性设置器; 集合属性应该只读取。

You should also remove the property setter; Collection properties should be read only.

您应该不会提高的PropertyChanged 事件时收集的变化。

You should not raise the PropertyChanged event when the contents of the collection change.

这篇关于INotifyPropertyChange〜没有的PropertyChanged射击练习时属性是一个集合和一个新的项目添加到集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆