View Model logic sometimes involves showing a modal dialog box. The dilemma has always been: how do you show the dialog while abiding by the rule that the View Model not reference the View? A common solution has become to create a dialog service class, then extract its interface for the View Model to consume. In my opinion, using the interface is only slightly better than using the actual class. It still looks to me like the View Model is referencing the View. Why attempt such a charade when the View Model's primary means of communication with the View is perfectly adequate?
Although the View Model must not reference View classes, the View Model can still talk to the View. If there wasn't such a capability, then displaying the View Model's properties to the user would be impossible. The communication method I am referring to, of course, is data binding. Data binding is already the primary means of communication between the View and the View Model. We can use it for showing a dialog box as well.
Showing a dialog box using the solution I have created involves two easy steps:
- Add the
MessageBoxHelper.Message
attached property into the View. - Within the View Model, set the property specified in the first step when you want the dialog box to be shown.
The View Model's property mentioned in these steps is of type
DialogPM
. This class contains no View-specific logic. It's purpose, rather, is to transport parameters for the
MessageBox.Show(...
method call from the View Model to the View and, if that method's result is important, back from the View to the View Model.
Download the
Qnomad CoreHelpers library to see the complete example.
Adrian loves facilitating suave user experiences via the latest and greatest GUI technologies such as Windows 8 Metro-style apps as well as WPF. More generally, he finds joy in architecting software that is easy to comprehend and maintain. He does so by applying design patterns at the top-level, and by incessantly refactoring code at lower levels. He's always interested in hearing about opportunities for full or part-time development work. He resides in Pennsylvania but can potentially travel anywhere in the country. (Writing about himself in the third-person is Adrian's new hobby.)