ViewModel属性上的奇怪行为,RaisePropertyChanged未被执行

Mar*_*one 1 c# wpf mvvm mvvm-light

我注意到在向ViewModel属性添加对象时,RaisePropertyChanged会出现奇怪的行为.

private List<string> _items;
public List<string> Items
{
    get 
    {
        if(_items == null){ _items = new List<string>(); } 
        return _itmes; 
    }
    set
    {
        _items = value;
        RaisePropertyChanged("Items");
    }
}
Run Code Online (Sandbox Code Playgroud)

我什么时候通过属性将对象添加到集合中

Items.Add("new string");
Run Code Online (Sandbox Code Playgroud)

RaisePropertyChanged永远不会被调用.

让RaisePropertyChanged按照我希望的方式运行的最佳方法是什么?

HCL*_*HCL 5

更改集合时将调用setter,而不是在集合的内容已更改时调用.您需要的是一个通知您变化的集合.看一下ObservableCollection<T>--class.注册其CollectionChanged活动,了解有关变化的信息.

具有setter
属性以下示例显示如何使用包含可观察集合的可设置属性.该示例的复杂性是因为可以从实例的外部设置集合.如果您不需要此功能,解决方案将变得更加简单.

private ObservableCollection<string> _items;
public ObservableCollection<string> Items {
    get {
        if (_items == null) { 
           // Create a new collection and subscribe to the event
           Items=new ObservableCollection<string>(); 
        }
        return _items;
    }
    set {
      if(value !=_items){
        if (null != _items) {
            // unsubscribe for the old collection
            _items.CollectionChanged -= new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_items_CollectionChanged);
        }
        _items = value;
        if (null != _items) {
            // subscribe for the new collection
            _items.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_items_CollectionChanged);    
        }
        // Here you will be informed, when the collection itselfs has been changed
        RaisePropertyChanged("Items");
    }
  }
}

void _items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
    // Here you will be informed, if the content of the collection has been changed.  
} 
Run Code Online (Sandbox Code Playgroud)

没有setter的属性
如果您不需要setable集合,请CollectionChanged在创建集合时注册.但是,您必须删除属性的setter.如果收集已更改,则不会通知更改:

private ObservableCollection<string> _items; 
public ObservableCollection<string> Items {
    get {
        if (_items == null) { 
           // Create a new collection and subscribe to the event
           _items=new ObservableCollection<string>(); 
           _items.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler
        }
        return _items;
    }
}

void _items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
    // Here you will be informed, if the content of the collection has been changed.  
} 
Run Code Online (Sandbox Code Playgroud)

其他信息有关集合更改的更多信息,请
查看INotifyCollectionChanged.在上面的例子中,你也可以使用更多通用的IEnumerable<string>INotifyCollectionChanged.