MVVM: Communication between the Model and ViewModels - wpf

I'm developing a WPF application using the MVVM pattern. I'm using MVVM Light library and I'm also trying to use a dependency injector (I'm considering Ninject and Unity).
I've read a lot of blog articles and I'm quite confused about the "proper" way of making my classes communicate with each other. In particular, I don't know when to use Dependency Injection and when to rely on the mediator pattern.
Lets consider an example. I have a ViewModel, lets call it DataViewModel, and the Data class that provides some kind of data.
How is it better to communicate between them:
A. Inject a dependency to DataViewModel with an interface of IData? This way Data will not have to rely on Messenger, but it will have to provide an event if the Data changes, and the ViewModel will have to subscribe to it.
B. Rely on the mediator pattern (implemented in MVVM Light as Messenger) and send messages between Model and ViewModel? This way it will not be necessary to use Dependency Injection at all, because whole communication will be based on messages.
Moreover, should my ViewModels have injected dependencies on other ViewModels, or it would be better just to rely on the Messenger? If the first, would it be necessary to define a separate interface for each ViewModel? I think that defining an interface for each VM will be an additional work, but maybe it is worth it.

Generally the ViewModel goes to a Service (as Prism calls it) to retrieve the data it needs. That service is pushed to the ViewModel via DI (Constructor Injection) although you could perform this another way via a ServiceLocator.
Therefore your ViewModel will hold a reference to a service which will abstract away the retrieval of your data. The data could be coming from a DB, XML file, who knows...the abstraction is there. So for your case of IData, the reference to that type will occur at some point in the ViewModel but not by way of any from of DI. If your IoC framework allows it (Prism does) you create mappings of interface types to concrete types and then retrieve those types via your container; such is the case with Unity.
Here is a brief example...Scripts is bound to the View and the ViewModel is injected into the View. Notice the use of the IScriptService to retrieve the data. The data coming back is a collection of IScript types, however we never formally injected that type into the ViewModel because we don't care about the type as a single entity we care about the type on a grandeur scale.
public ScriptRepositoryViewModel(IUnityContainer container, IScriptService scriptService, IEventAggregator eventAggregator)
{
_container = container;
_scriptService = scriptService;
_eventAggregator = eventAggregator;
}
public ICollectionView Scripts
{
get
{
if (_view == null)
{
_view = CollectionViewSource.GetDefaultView(_scriptService.Scripts);
_view.Filter = Filter;
}
return _view;
}
}
When you make your way to the View, the same case can be had there, the View will get injected via DI (Constructor Injection) with the ViewModel. I would not make other ViewModels depend on each other, keep them isolated. If you begin to see a need for coupling take a look at the data you are trying to share, more often then to that data needs to be abstracted out further and not become coupled to any ViewModel.

There is more than one good solution to your problem,
I suggest you to use some single interface in your data models, put it in a base class, this interface will allow your data objects to communicate with the outside world.
For the view models inject not the data but an interface that can retrieve data for you, the data will expose events that the vm can register to them after he gets them.
data oject should not know who holds him, view model knows what kind of data he holds but I dont recommend to inject this data due to flexibility issues.

Related

Correct way to handle commands that rely on multiple view models

I'm relatively new to WPF and MVVM and i am trying to understand how to use commands correctly when they have dependencies in more than 1 view model.
A couple of examples:
In my current application i have a RelayCommand which causes a save action to occur in a couple of different view models (they write a couple of different files). Currently i am handling this using a the mvvmlight messenger to send a message to those view models to get them to do the save which i think is the correct way to do it as it avoids having to provide some kind of delegate or event to/on those view models.
I have a RelayCommand in a view model that has a CanExecute method which relies on the state of 2 other view models. I've currently handled this via the mvvmlight messenger as well by having changes in the view models the CanExecute method depends on message that their state is now valid for the operation. This seems messy but the only alternative i could think of was to use a delegate or event effectively weaving the view models together which i believe i should be avoiding.
Is there some generally accepted way to deal with this which i am missing?
In general your view model layer should have a 1:1 relationship with your view, there should be no good reason for a "Save" function to exist in a view model which is then called by another view model.
What it sounds like you should be doing is putting that logic into a service i.e. something like this:
public interface ISerializationService
{
void Save(SomeData data);
}
Then you need an implementation for this service that does the actual work:
public class SerializationService : ISerializationService
{
void Save(SomeData data)
{
// actual save happens here
}
}
Your view models should then contain properties that point to instances of these services:
public class MyViewModel : ViewModelBase
{
[Inject]
public ISerializationService SerializationService { get; set; }
// called when the user clicks a button or something
private void ButtonClickCommand()
{
this.SerializationService.Save(this.SomeData);
}
}
The only question remaining is "What sets the value of SerializationService?", and for that you need a dependency injection framework. There are plenty out there, MVVMLight installs one itself, but Ninject is the de-facto standard. When implemented properly the injection framework will create all view models for you and then "inject" the dependencies, i.e. your SerializationService property, of type ISerializationService, will be initialized with an instance of your SerializationService class (which in a case like this will also be configured to be a singleton).
Dependency Injection takes a bit of work to get your head around but once you start using it you'll never look back. It facilitates complete separation-of-concerns whilst alleviating the need to pass pointers to everything all up and down your architectural hierarchy.

Notification from ViewModel to View

I need to send notification from ViewModel to View in MVVM WPF application. In most cases it will be simple MessageBox on View side. Is it unacceptable violation of MVVM pattern to use types like System.Windows.MessageBoxResult or System.Windows.MessageBoxImage in ViewModel (in this case VM must reference UI-specific libraries)?
I need to pass title, message and notification type from VM and by creating custom enumerations I am in fact copying existing functionality from .NET Framework.
You don't need notification mechanism. That's one option. Another is using simple service class:
public class ViewModel
{
IDialogService _dialogService; //ctor injection or use service locator
public void CommandExecute()
{
_dialogService.ShowMessageBox(...);
}
}
public interface IDialogService
{
bool? ShowMessageBox(params....);
}
public class DialogService : IDialogService
{
public bool? ShowDialog(params...)
{
MessageBox.Show(params...);
}
}
I find this approach more straightforward, easier to understand and easier to debug. Messaging may easily turn into memory leak and in this case I don't see any benefit over my approach.
EDIT:
Will you use custom enum in ShowMessageBox parameters, or will you use
System.Windows.MessageBoxImage?
First of all, ViewModels belong to presentation layer. It is OK to use enums like System.Windows.MessageBoxImage in ViewModel.
In MVVM, ViewModels are separated from Views because of following reasons:
ViewModels expose data and logic from Model in such way that is easily consumable from Views (e.g DataBinding)
ViewModels are easier testable
ViewModels provides better design time support (Blendability, test data)
ViewModels separates application logic from the actual presentation markup which makes it easier to understand (readbility)
Does using enum like System.Windows.MessageBoxImage breaks any of the points above? The answer is no.
If you wanted to reuse IDialogService and your ViewModels on multiple platforms, for example WPF, UWP and Xamarin, then you need to create your own enum, because it may not exist on all platforms. The golden rule is: don't add another layer of abstraction if you don't need it.
You could have the view implement an interface, say INotificationService and then pass the view to the view model constructor. That won't violate MVVM, and you will still be able to bind the view model to the view using the DataContext property on the view.
I decided to keep ViewModel as clean of UI (View) stuff as possible, so I will create custom enumeration inspired by MessageBox and tailored exactly to my needs.

Master-Detail relation with inheritance in a WPF MVVM application

I think this is a rather basic question, but I haven't been able to find an answer to this.
I have the following scenario:
Without using any form of EntityFrameWork I have a PersonViewModel and a PersonDetailsViewModel, which inherits from the PersonViewModel. In my PersonView I display a collection of PersonViewModels in a grid. I have properties like Name, DateOfBirth etc, as columns. When I double click on a person a PersonDetailView pops up which is bound to a PersonDetailsViewModel. In this View there is extra information shown about the person (Gender, SocialSecurity number etc.). The user I allowed to edit all properties.
Now I wonder what the best/common approach is to make sure that the PersonViewModel gets updated with the values that have been editted in the PersonDetailsViewModel.
I can think of several options. For starters I could opt for not using different ViewModels, but instead use PersonDetailViewModels to show in the grid, but the downside to that is that I would need to retrieve a lot of unnecessary data per ViewModel.
I can also synchronise the corresponding properties after the PersonDetailsView closes.
The third option I can think of is that instead of inheriting from the PersonView I will include a property in PersonDetailsView that is of the type PersonView and expose it's properties and use it for binding in the PersonDetailsView. All other extra properties in PersonDetailsViewModel will then be retrieved in it's constructor.
In my experience, the best way to update view models who share the same data is to use the Mediator pattern to send a notification message that the data has updated.
In order to have a good object oriented design we have to create lots
of classes interacting one with each other. If certain principles are
not applied the final framework will end in a total mess where each
object relies on many other objects in order to run. In order to avoid
tight coupled frameworks, we need a mechanism to facilitate the
interaction between objects in a manner in that objects are not aware
of the existence of other objects.
Source http://www.oodesign.com/mediator-pattern.html
It is syntactically important to your design that the notification says what has happened (the data was updated) and not what should happen (data gets reloaded) because that response may not stay the same as the system evolves.
Often, common MVVM libraries have Mediator implementations in them. For example, Prism's EventAggregator.
in Addition to Sheridans answer. i would expose the Detail as a property of type PersonDetailsViewModel
public class PersonViewModel
{
public PersonDetailsViewModel Detail {get;set;}
}
then your xaml looks simply like that
<TextBlock Text="{Binding Detail.Gender}"/>
EDIT1: in addition to the comments above
i would not do any inheritence (thats what user1087702 wrote in his question). i would simply create 2 classes: PersonVM and PersonVMDetail. And if the request is, to show Details from my person object, why in hell shouldn't i just create a public Property in my PersonVM class of type PersonVMDetail - to fullfill this request?
The simplest way to achieve your requirements would be to add a constructor to your PersonViewModel class that takes a PersonDetailsViewModel instance and updates its common properties:
public PersonViewModel(PersonDetailsViewModel personDetailsViewModel)
{
Name = personDetailsViewModel.Name;
...
DateOfBirth = personDetailsViewModel.DateOfBirth;
}
...
PersonViewModel = new PersonViewModel(PersonDetailsViewModel);
Of course, this doesn't have to be in the constructor... it could just as easily be a method in the PersonViewModel class, or even a helper method in a separate Factory Pattern class, it's up to you.

MVVM model instantiation

Following WPF MvvmFoundation, linking the View with the ViewModel has many choices like described on http://www.paulstovell.com/mvvm-instantiation-approaches.
However their example has nothing about how to link the ViewModel with the Model.
Traditionally I created the model first and then one or more views that render it. It seems that MVVM pushes people to create the View, which creates the ViewModel, which create the Model. I hope it's not the case as wiring a complex business model with various ModelView can else be tough.
How do you instantiate your business model classes in MVVM and link them with your ViewModels?
I normally pass Model objects as constructor params to VM. I use App class as the controller which will initialize MainWindow, MainWindowViewModel with the main model. There after the MainWindowViewModel takes care of initializing other VMs with appropriate model objects.
private void Application_Startup(object sender, StartupEventArgs e)
{
mainWindow = new MainWindow();
mainWindow.DataContext = new MainWindowViewModel(new Model());
mainWindow.Show();
}
You create your BusinessModel classes inside your ViewModel.
So in your CustomerViewModel you would say this.CurrentCustomer = new CustomerModel(), and your CustomerView would bind to the CurrentCustomer property on the ViewModel
If you are interested, I wrote up a simple sample using MVVM as an example of how the View, Model, and ViewModel interact.
I use dependency injection/MEF to do this. Just export all of my model classes all the way down the chain, and have them imported for me automatically into the ViewModel constructor.
I take a variety of different approaches depending on the situation. I've found that when it comes to getting this data linked, one size does not fit all.
For simple cases, I will have the ViewModel and the Model be the same thing. Obviously not that good for all cases, but sometimes there is just no need to go the extra mile to split the M from the VM. (Great for cases where you have, say, listbox items that have scant information)
Sometimes, especially when the model is a chunk of code you don't have access to (written by another developer) it is easy to subclass the model, and add all of your VM things (observable properties, etc.) on to it.
Lastly, I will use the approach that is mentioned by Souvik. Construct the VM with the model information that you want to use as a parameter, or allow it to be passed in otherwise. This is probably the most common approach for my larger and more complex Model / ViewModel relationships.
I am auto-passing IRepository instance to VM constructor using IoC container and everything VM needs to do with models is done via this repository. Repository is class which: Create, read, update and delete data. When I need to show some view (window), I use IViewService.ShowDialog(viewModel As ViewModelBase). In implementation of IViewService, there are views registered with VMs, so VMs only need to know other VMs and not their views (like "Show me view for this view model").

MVVM: Caching data for ViewModels

In my WPF MVVM application I use dependency injection container. When I want to retrieve some data from my Model, I use an asynchronous interface to query the Model and fill the ObservableCollection in my ViewModel (I understood it thanks to the answers to my previous question).
I'm looking for a best solution to handle a following situation. There is a collection of objects I'm retrieving asynchronously from my Model. I want to use the same data to build observable collections in two different ViewModels, as I want to display that data in two different windows. The Model domain objects are going to be wrapped in different ViewModel objects as the wrappers needs to prepare the domain objects to be displayed. I don't want to retrieve data from the Model separately in each ViewModel, but to do it once, as it might be a time-consuming operation.
I've seen a few examples and everywhere a single ViewModel is responsible for retrieving data from the Model service. What should I do to use the once retrieved data in more than one ViewModel?
I think that I should introduce another layer of abstraction between my Model and ViewModels that will handle the caching of retrieved data and every ViewModel that wishes to utilize this data will have the dependency to this layer.
Is this a good idea?
That missing link would be a service as referenced within Prism.
The model classes are typically used
in conjunction with a service or
repository that encapsulates data
access and caching.
You'll note in the previous question that I am making use of a service within that ViewModel.
public ScriptRepositoryViewModel(IUnityContainer container,
IScriptService scriptService, IEventAggregator eventAggregator)
{
_container = container;
_scriptService = scriptService;
_eventAggregator = eventAggregator;
}
public ICollectionView Scripts
{
get
{
if (_view == null)
{
_view = CollectionViewSource.GetDefaultView(
_scriptService.Scripts);
_view.Filter = Filter;
}
return _view;
}
}
Note the IScriptService being injected into the ScriptRepositoryViewModel. That service actually implements caching and varying logic so that whoever polls for the Scripts will get a cached copy or perhaps a fresh copy; the consumer doesn't need to care.
In your instance with your two ViewModels needing the same data you could follow the same pattern of injecting a service into each ViewModel. When the ViewModel calls the service to retrieve the data you can implement logic to not fetch the data from the back end unless it has been stale for 10 minutes or whatever behavior you so desire. It has been abstracted at that point and you are free to do what you need; allowing N ViewModels to consume the data form a central location without un-needed load.
Yes you have to introduce another layer, irrespective of caching or not in my applications ViewModels are used for sole purpose of binding to Views and they don't contain any logic of retrieving data from Business (Service) layer
Use RegionManager["nameRegion"].context, the ViewModel is the context of the View, that yo can share with other ViewModels

Resources