Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Are you sure?" prompts. Part of the ViewModel or purely the view?

Tags:

c#

mvvm

wpf

I've been toying with where to put "are you sure?" type prompts in my MVVM WPF app.

I'm leaning towards thinking that these are purely part of the View. If the ViewModel exposes a DeleteCommand, then I would expect that command to delete immediately.

To integrate such prompts into the ViewModel, it would have to expose a separate RequestDeleteCommand, a DeletePromptItem property for binding the prompt against, and which could also double as a trigger to show the prompt.

Even with this, there's nothing stopping a unit test calling DeleteCommand directly, unless I put specific logic in the ViewModel to require DeletePromptItem to match the item supplied as an argument to DeleteCommand.

However, this all just seems like noise in the ViewModel to me. The prompt is more a user interface issue to guard against misclicks etc. To me this suggests it should be in the view with a confirmed prompt calling the DeleteCommand.

Any thoughts?

like image 897
GazTheDestroyer Avatar asked Apr 19 '12 11:04

GazTheDestroyer


People also ask

Should every view have a ViewModel?

For a best mvvm pattern implementation each view must have the own viewmodel, and don't share anythings with other.

Can a ViewModel have multiple views?

It's possible that having two separate views is what you want, but it's just something to consider. Show activity on this post. Define the viewmodel as singleton (code smell) or. Using the RegionContext (for full description see the prism doc)

Can ViewModel have reference view?

In "pure" MVVM, the ViewModel shouldn't really reference the View. It's often convenient, however, to provide some form of interface in the View whereby the ViewModel can interact with it.


1 Answers

The prompts should definitely not be part of the ViewModel, but this doesn't necessarily mean that the best solution is to hardcode them in the View (even though that's a very reasonable first approach).

There are two alternatives that I know of which can reduce coupling between View and ViewModel: using an interaction service, and firing interaction requests. Both are explained very well here; you might want to take a look.

The general idea is that you abstract how asynchronous interactions are done and work with something more similar to event-based logic while at the same time allowing the ViewModel to express that it wants to interact with the user as part of an operation; the net result is that you can document this interaction and unit test it.

Edit: I should add that I have explored using Prism 4 with interaction requests in a prototype project and I was very pleased with the results (with a bit of framework code going you can even specify what's going to happen on a specific interaction request entirely in XAML!).

like image 155
Jon Avatar answered Sep 28 '22 16:09

Jon