1
votes

Here is a simplified version of the model for my WPF application:

Employee
  +Name:string

Client
  +Name:string
  +PhoneNumber:string

Appointment
  +Employee:Employee
  +Client:Client
  +DateAndTime:DateTime

My application has a few main pages organized with a TabControl. Each TabItem has an associated View and ViewModel. On one page, there is a DataGrid showing all Appointments with several specific details, like the client's phone number. One a second page, there is another DataGrid showing all Clients. These DataGrids are bound to different ViewModels since they are on different pages. My ViewModels are implemented as mere wrappers of the Model that implement INotifyPropertyChange.

And there is the problem: if the user modifies a Client's phone number on the second page, the ViewModel for that page is correctly updated (and the Model through it), but the ViewModel for the first page is not notified that a change occured. When I go back to the first page, any Appointment with that Client that was onscreen then still shows the old phone number until I do something that will cause an update of that ViewModel.

How should I solve this? Should a common ViewModel be shared between pages? Should the Model somehow notify all ViewModels when a change is made (the model currently knows nothing about the ViewModels)? This is my first MVVM project so I'm not sure how things should be done.

To make things more complex, on my first page I use a calendar control and use its SelectedDate property to determine which appointments to display. The ViewModel for that page therefore has to keep its own cached list of appointments that it updates whenever the SelectedDate changes or an appointment is added or removed.

Thanks for any help with this.

2

2 Answers

0
votes

You probably want some sort of messaging going on, notify and listeners etc. There are many ways to do it, check out MVVM Light, it has a built in method and this post has an example of its use...

http://blog.galasoft.ch/archive/2009/10/18/clean-shutdown-in-silverlight-and-wpf-applications.aspx

0
votes

The Model should never be aware of the ViewModel, just like the ViewModel should never be aware of the View.

If you can't introduce MVVM Light or some other framework, put an event on the model (or have it implement INotifyPropertyChanged), and the ViewModel can subscribe to that event and raise a PropertyChanged event of its own.

Just make sure when the ViewModel is leaving scope that it unsubscribes from the Model.

The reason this works is because you're not making the Model directly aware of the ViewModel. You're just allowing the Model to yell "HEY BUDDY I CHANGED!". Then anyone listening can take appropriate action without violating any patterns, and since ViewModels are allowed to pay attention to Models, this works out.

And if five different ViewModels are subscribed and wired up to different views but paying attention to the same model, they'll all get the updates.