在实体修改的 ViewModel 中注册更改

Register changes in the ViewModel on Entity modifications

我有一个包含多个 viewModel 的 observableCollection,每个 viewModel 都绑定到一个实体模型。 viewModel 还包含几个计算文本值:

public class SampleViewModel : NotificationObject
{
    private Entity _myModel;
    public Entity Model
    {
        get;
        private set;
    }

    public string HasEntries
    {
        get
        {
            if(Model.Entries.Count > 0)
                return "Model has Entries";
            else
                return "Model has no Entries";
        }
    }

我现在如何通知视图中的 ViewModel 和 ObservableCollection 在模型更新时 HasEntries-属性 已更改?

sampleViewModel.Model.Entries.Add(entry);

编辑:

澄清一下:我有时会通过在条目实体中设置引用来向模型添加条目:

private void addEntry(){
    Entry t = new Entry();
    t.IDModel = sampleViewModel.Model.ID;
    dataAccessLayer.AddEntry(t);
}

所有这些都发生在相同的上下文中,因此该对象将显示在 sampleViewModel 中。我只需要找到一种方法来捕获此事件并通知 viewModel 有关新添加的对象。

为什么不直接创建一个方法来添加条目并通知更改,而不是直接公开您的模型。

public class SampleViewModel : NotificationObject
{
    private Entity Model {get;set;}

    public string HasEntries
    {
        get
        {
            if(Model.Entries.Count > 0)
                return "Model has Entries";
            else
                return "Model has no Entries";
        }
    }
    public void AddEntry(Entry entry)
    {
         Model.Entries.Add(entry);
         //Execute you nofity property changed
         NotifyPropertyChanged("HasEntries");   
    }
}

然后

sampleViewModel.AddEntry(entry);

我找到了一个非常简单的解决方案。事实证明,当 属性 更改时,每个实体都会自动引发 属性Changed-Event。我所要做的就是将模型的 PropertyChanged-Event 绑定到 viewModel:

Model.PropertyChanged += Model_PropertyChanged;

在我的具体情况下,因为它是一个集合:

Model.Entries.AssociationChanged += ModelEntries_PropertyChanged;

protected void ModelEntries_PropertyChanged(object sender, CollectionChangedEventArgs)
{
    RaisePropertyChanged(() => this.HasEntries);
}