Thursday, January 20, 2011

WPF Dialog Service via Binding

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:
  1. Add the MessageBoxHelper.Message attached property into the View.
  2. 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.

No comments: