I have a WPF-Application based on MVVM-Pattern. All works fine. In the business logic of View-Model I need to invoke some dialogs. I have implemented it through an interface(interface implementation is in a View layer).
For the dialogs I need to set the parent window, so the function in interface has an argument "parentView".
In my ViewModel I have a property "View" from type "object" for a parent window. This property I put as argument for instantiating of a dialog.
Since "View"-property is from type "object" and is set from View layer and forwarded back to the View layer, the View-Model layer has no dependencies on View layer.
What do you think, have I broken the MVVM-Pattern?
What do you think, have I broken the MVVM-Pattern?
No. The view model have no dependency upon the view, it only knows about an interface that you could easily mock in your unit tests. So this doesn't really break the pattern as long as "View" is just an abstraction of something.
For type-safety reasons you should probably consider changing the type of the parameter from object
to a strongly-typed interface type though.
No friend - this is a solved problem.
I mean there is no real beauty in all the solutions, but you could use a Dialog-Service for example.
A real easy implementation on this would be a Singleton
that has a static Field with your Main-Window
. Now you can call your Dialogs from this class.
I actually think MahApps for example goes like this, but they register it the fancy way:
<controls:MetroWindow
x:Class="SomeMetroWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"
xmlns:Dialog="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro"
Dialog:DialogParticipation.Register="{Binding}"> <!-- watch this pls --->
<!-- ... --->
</controls:MetroWindow>
Here is an example for general implementation. And here another arcticle about arcticles of this topic.
As I said - not really beautiful, but solved.