Register changes in the ViewModel on Entity modifications

137 views Asked by At

I have an observableCollection containing several viewModels which are bound to an entity model each. The viewModel additionally contains several calculated text values:

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";
        }
    }

How can i now inform the ViewModel and the ObservableCollection in the View that the HasEntries-Property has changed when the model gets updated?

sampleViewModel.Model.Entries.Add(entry);

Edit:

To clarify: I sometimes add an entry to the model by just setting an reference in the entry-entity:

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

All of this happens in the same context and so the object will show up in the sampleViewModel. I just have to find a way to catch this event and notify the viewModel about the newly added object.

2

There are 2 answers

0
narain On BEST ANSWER

I found a pretty easy solution. As it turns out every entity automatically raises a propertyChanged-Event when a property is changed. All i had to do was to bind the PropertyChanged-Event of the Model to the viewModel:

Model.PropertyChanged += Model_PropertyChanged;

And in my specific case because it is a collection:

Model.Entries.AssociationChanged += ModelEntries_PropertyChanged;

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

Instead of exposing your model directly, why not just create a method that adds entries and notifys of the change all in one.

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

Then

sampleViewModel.AddEntry(entry);