In the last post, I introduced you to my DynamicGridFormationBehavior, which gives you the ability to dynamically change a grid’s formation, using only Xaml. In this post, I want to introduce you to another behavior, called ConfirmationBehavior.
First let’s set the context. Assume that we have an application that handles customers’ information, and allows CRUD operations on it. The client asked that before any critical operation on the data (deleting a customer for example), a confirmation message will appear.
If you’re following the MVVM pattern in your WPF applications (and you should), you will probably end up with a ViewModel with an ICommand to handle the delete request, and a View with a button which will be bound to the command.
But what about the confirmation? Should it be part of the ViewModel, or part of the View’s code-behind?
Putting the confirmation code inside the ViewModel will sacrifice its testability, since the ViewModel will explicitly call MessageBox.Show (or some other alerts-related UI), preventing us from easily writing automatic unit tests for it. Furthermore, placing a UI specific code inside the ViewModel is a violation of the SRP principle.
Putting the confirmation code inside the View’s code-behind will not only sacrifice the testability, but also the maintainability of the application, since we will have to duplicate the entire confirmation code over and over again for each button that invokes a command that needs to be confirmed.
By encapsulating the confirmation code into a behavior, our code will be testable, since the ViewModel will not contain any UI-related code, and maintainable, since the application’s layers will be clearly separated, and the behavior will be reusable.
Let’s take a look at the behavior’s implementation:
Please note the following:
- The generic type parameter enables us to inherit and customize the behavior for more specific types (like ToggleButton, as you can see above).
- The behavior allows us to customize the message and caption of the confirmation.
- Currently, the behavior is using System.Windows.MessageBox, which is impossible to style. You can change it to use a different control if you wish (like the one in the Extended WPF Toolkit).
- The non-generic ConfirmationBehavior is there just because not all Xaml schemas have a support for generics.
And the usage:
As you can see, by using the behavior, we kept our ViewModel clean and made our intentions clear for anyone who is reading the Xaml.
The code is available on GitHub, as part of my WPFUtils project.