I’m prototyping a WPF application with the MVVM pattern. Following an answer to this question I have set up a ModelProviderService which exposes models as properties. The consumers of the service are the viewmodels, i.e. they pull their models from the service instead of instantiating them theirselves.
class ModelProviderService {
private LoginModel loginModel;
public LoginModel LoginModel {
get { return loginModel; }
set { loginModel = value; }
}
private ProjectsModel projectsModel;
public ProjectsModel ProjectsModel {
get { return projectsModel; }
set { projectsModel = value; }
}
public ModelProviderService() {
loginModel = new LoginModel();
projectsModel = new ProjectsModel();
}
}
Now, here is what shall happen:
- A viewmodel changes a property of e.g. the
LoginModelproperty. - The viewmodel pushes the model property back to the service by setting its property:
modelService.LoginModel.MyProperty = localLoginModel.MyProperty; - The service shall publish a message: “Hey, my model of type
LoginModeljust changed.” - Any other viewmodel that has subscribed to this message will pull this changed model from the service.
How can I implement:
- the “broadcast message”?
- the subscription to the message?
You could use a
MessageBusorEventAggregatorto publish messages to subscribers by using weak references. Take a look at my implementation (or the NuGet packgage).It can also marshal the message handling to the UI thread for you (if you need to update UI components) by applying the
HandleOnUIThreadAttributeon theHandlemethod.Usage in your case would be something like:
If you want to know more about the inner workings and how to implement this; Check out the source code in the GitHub repository. Feel free to use the code as you like 🙂