UI Validation before executing RelayCommand WPF
I'm new to WPF and I tried to implement a demo application with RelayCommand.
My question is this:
If i want 开发者_开发百科to execute a command which has to ask the user if he's sure he wants to execute it first - what's the best way to do it? I need an "are you sure?" messagebox to pop. However, the command is executed on the viewmodel, and of course I don't want to mess with GUI there.
Thanks
The way I deal with this is to have an IDialogService
interface that is registered in your IOC and available to your ViewModels.
The service then provides various ways of interacting with the "user". So you could have a ConfirmMessage method, that returns true or false based on the user accepting a dialog.
Then for unit testing say, you can have a different IDialogService
implementation that allows you to feed canned responses to your ViewModel when under test.
I just ran into this myself. I'm using MVVM Light, and I used the Messenger to accomplish this.
I had my ViewModel send a GetConfirmationMessage
, which I had registered in the code-behind. Within the handler for GetConfirmationMessage
, I popped up the dialog box and got the reuslts. If the user clicked on OK, I then sent a ConfirmationReceived
message, which was handled by the ViewModel to do the appropriate updates.
精彩评论