我有一个ViewModel,它包装了模型对象的实例,并充当模型和View之间的接口。就我而言,该模型具有一个集合,该集合可以通过视图模型中的可观察集合连接到视图。
例如:
public class NotificationBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetField<T>(ref T field, T value, [CallerMemberName] String fieldName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
RaiseChangedEvent(fieldName);
return true;
}
protected T SetProperty<T>(T property, T value, [CallerMemberName] String propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(property, value)) RaiseChangedEvent(propertyName);
return value;
}
protected void RaiseChangedEvent(string changedObjectName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(changedObjectName));
}
}
public class ViewModel : NotificationBase
{
public ViewModel(ref Model model)
{
_model = model ?? throw new ArgumentNullException("Model cannot be null");
}
public ObservableCollection<Thing> ViewModelCollection
{
get { return _model.ModelCollection; }
set { _model.ModelCollection = SetProperty(_model.ModelCollection, value); }
}
private Model _model { get; set; }
}
我的问题是:_model.Collection
以及ViewModelCollection
更改后如何使视图知道?
注意:Model.Collection
实际上是一个ObservableCollection
,但我不知道如何将CollectionChanged
事件传递给ViewModel,然后传递给View。