tags:

views:

66

answers:

2

I have a project where the Model can be altered from one of many Presenters. How can I ensure that the Views are notified of any changes?

The usual notification comes from the code behind (or Presenter if using Caliburn), but if the Model was changed from another source how can I properly inform the View(s) of the change?

A: 

I would assume that the view is bound to the model and therefore the bindings would take care of this. Am I missing something?

Drew Noakes
It's the ViewModel that the View binds to, not the Model directly
Alex Baranosky
Ok that makes sense. You didn't mention the ViewModel at all in your question, nor that you were using MVVM.
Drew Noakes
+2  A: 

Either the model needs to support change notification, or you need a "single point of truth" such as a service, which itself has change notification. Your view models would then attach to this change notification and ensure the changes are passed onto the view.

Simplified example:

public interface IDataService
{
    ICollection<Customer> Customers
    {
        get;
    }

    void AddCustomer(Customer customer);

    void DeleteCustomer(Customer customer);

    event EventHandler<EventArgs> CustomersChanged;
}

public class SomeViewModel : ViewModel
{
    public SomeViewModel(IDataService dataService)
    {
        _dataService.CustomersChanged += delegate
        {
            UpdateCustomerViewModels();
        };

        UpdateCustomerViewModels();
    }

    public ICollection<CustomerViewModel> Customers
    {
        get { ... }
    }

    private void UpdateCustomerViewModels()
    {
        ...
        OnPropertyChanged("Customers");
    }
}

Now, as long as all your view models use this service, you can have them use the event(s) on the service to detect changes they're interested in. Of course, depending on your exact requirements, you may be able to reduce the amount of work done when changes are detected.

HTH, Kent

Kent Boogaart
Thanks Kent, I think that sounds about right. Appreciated.
Alex Baranosky
worked like a charm.
Alex Baranosky