Cancel a windows close from a View Model? - wpf

I've a WPF application which allows me to edit some data.
I would like to make that if we try to close the application, the user must acknowledge that he will lost its modifications.
But here we are, I got several problem:
There is no "Closing" commands on the windows object(I can execute a command when I have an event from the code behind I guess)
I don't know how it's the recommended way to cancel something with the MVVM pattern? Normally I would have put the e.Cancel = true;, but we can't because it's a command
So how would you ask the user if he is sure to close the windows, with the MVVM pattern?

The concept is to add a behavior to your window that "hooks" into the window closing event. Once the behavior is hooked in, you can perform just about any action you need without violating the principles of MVVM. Check this link for information on how to create a window closing behavior:
http://gallery.expression.microsoft.com/WindowCloseBehavior/
Hope that helps.

Since you tagged this question as "mvvm-light", you can check the EventToCommand in MVVMLight. It may meet your needs.
This question is similar:
Handling the window closing event with WPF / MVVM Light Toolkit

Related

Rigid adherence to the MVVM pattern?

I am building a WPF application and using the MVVM for the first time. Overall using MVVM has been very interesting and one of the major benefits is the nice separation between the view and the model classes. It kind of disciplines (at least young developers) to not to mix them together.
We have a scenario where a window needs to be closed on a button click after a confirm message box. Now this can achieved the old-way by handling the button click event and closing the window in the Window class itself. Or we can do it MVVM way by creating a command in ViewModel, call Window to show message box..etc.
I understand what needs to done here, but my question is - is it necessary to use MVVM commands in all cases? Are there exceptions where we should not use commands e.g. simple UI actions? Are we not overusing MVVM here? What exactly will the benefits doing everything the MVVM-way?
Or we can do it MVVM way by creating a command in ViewModel, call Window to show message box..etc.
Let me pick this apart, mainly because IMVHO I see this done wrong all the time - a lot of people try to do too much in the VM. First of all, ask yourself the question:
Is the prompt related to the data or business rules in any way whatsoever?
If it isn't, i.e. it is simply a "are you really sure?" type prompt, then this SHOULD be done purely within the code behind of the view. The only time the viewmodel needs to have any knowledge or take any action is when it actually has something to do with the viewmodel, in which case you should expose a command from the VM, but the actual window closing is still done from the code behind of the view.
The VM should know nothing about the view that it is bound to, that is one of the purposes of the MVVM pattern. It can expose commands, but it shouldn't know that a user has interacted with a specific UI element1, and it shouldn't directly know that the window is about to be closed. It is okay for the VM to prompt (via a dialog service, which you do have, yeah?) that the current data is unsaved, but it doesn't know about the window in general because it doesn't know how its data is presented.
Sometimes you will walk a fine line, and it is easy to over analyze whether something should be done purely from the view, purely from the VM, or as a mixture of both. If you remember the role of the VM, and remember that it is okay to have code behind in the view (provided it is only doing view related stuff and handing VM stuff off to the VM) then 99% of the time you won't have a problem.
1 For example, the VM shouldn't know or care whether the user just clicked a button, hyperlink, or touched a hot spot in an image. The same command can be used to handle any of this.

Getting started with UIAutomation

I'm trying to find a good resource to get started with UIAutomation. I need to simulate mouse input in a WPF application. Are there any good examples out there? I couldn't find any, and the MSDN documentation seems too extensive.
UI Automation is not really intended to simulate mouse clicks. It is meant to expose the user interface in a programmatically-accessible fashion.
It organizes controls in a hierarchy that can be easily traversed/navigated by screen readers or similar applications. And, it uses control patterns to allow users to interact with the controls.
A Button for example can expose the InvokePattern via it's automation peer. You can simulate a click using the Invoke method on that pattern. This is done independently of the mouse, so there would be no mouse over/enter/leave/down events, just a Click event.
You can use mouse class with UIAutomation. But as CodeNaked rightly said, we should use UIAutomation patterns for mouse like operations and it is not good practice to use mouse class.
You can refer this code project article to start with UIAutomation.
I hope this will help you.

How to execute a command and change focus after a keypress in a WPF app

I have a WPF app that uses MVVM Light and I wish to both execute a command on the view model and change the keyboard focus to a specific control when the user presses ALT+SHIFT+C.
Is it possible to achieve this in an elegant way?
It depends on how the shortcut key is created (if it's like Visual Studio or more like Windows - it means if you have to hold only ALT or all the keys).
But whatever the logic, You will have to first bind an Event to a Command (it might be the event keydown of one of your controls).
In MVVM Light, you will have to use Interaction.Triggers with EventToCommand (there's a lot ot explanations on google and SO)
The logic would be put here in you command.
Then a dependecy property as show here could be implemented for getting the focus.

WPF interactionRequests in PRISM

I have what, on the face of it, seems to be a really simple requirement - to be able to show a messagebox from within the view model of my WPF prism application.
Reading the documentation everything sounds good when I'm reading about Interaction Requests but I then find out that WPF doesn't support PopupChildWindowAction.
How are people getting around this. Basically I want a Messagebox in my shell module / or a infrastructure module that will subscribe to events and popup when that event is published.
Another issue I had was I want the popup to be centered on the parent window (the shell).
Just wondered how other people approached this. There seem to be a number of different ways to go but neither seem to fit the bill exactly.
From A CodePlex post by Karl Shifflet:
I've written a WPF version of the Interaction Request for my the Box MVVM Training here:
http://visualstudiogallery.msdn.microsoft.com/en-us/3ab5f02f-0c54-453c-b437-8e8d57eb9942
Install this Visual Studio Extension.
Create a new project with the MVVM Training Template.
Check out DialogInteractionRequestView.xaml and its implementation.
Cheers,
Karl
Use the RegionPopupBehavior from Prism 2.2 RI.
Use the EventAggregator in PRISM to subscribe to events, and have an in-memory presenter that listens for an event and then creates a view using the event data and calls ShowDialog on the view.
The dialog result can then be used to publish a 'response' event that would be routed back to the process that initiated the event that resulted in the display of the dialog.
Since PopupChildWindowAction is only in Silverlight, I have created my own PopupAction by inheriting from TriggerAction class and simply overridden body of Invoke() method to bring up a PopupWindow where I can pass any UserControl from xaml within the prism interaction trigger tag. From within ViewModel I am raising interactivity request event which triggers my PopupAction in view and opens the popup with desired user control being displayed onto it. Seems to work. I'll need to polish the example more. But here is a link -
http://wpfgrid.blogspot.com/2013/01/simple-prism-mvvm-way-to-display-dialog.html#step3

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.

Resources