繁体   English   中英

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

[英]Register changes in the ViewModel on Entity modifications

我有一个observableCollection包含几个viewModel,每个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-Property已更改?

sampleViewModel.Model.Entries.Add(entry);

编辑:

澄清一下:我有时只通过在entry-entity中设置引用来为模型添加一个条目:

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);

我发现了一个很简单的解决方案 事实证明,当属性发生变化时,每个实体都会自动引发propertyChanged-Event。 我所要做的就是将Model的PropertyChanged-Event绑定到viewModel:

Model.PropertyChanged += Model_PropertyChanged;

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

Model.Entries.AssociationChanged += ModelEntries_PropertyChanged;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM