I am able to bind buttons and menu items with ICommand
and close the windows. It is exactly as described in the tutorial WPF Apps With The Model-View-ViewModel Design Pattern - via the Command
property accessible in XAML.
But it is not described or implemented in the tutorial how to close by pressing the standard 'Close' icon on the top-right of the window. I need to perform some clean up in my application. My question is how to bind a Command
to the close event, so that it is executed when the user presses the close icon (not buttons or menu items - I know how to manage such cases).
How should this be handled to avoid violating the MVVM approach? Thanks!
I would bind a Command to the Application's Exit event
I like using the AttachedCommand
behavior found here for binding Commands to Events, although I know you can also accomplish the same thing using Blend's Interaction Triggers.
The MVVM Light Toolkit contains a behaviour called EventToCommand, which gives you an easy way to bind a command to an event.
The following XAML snippet shows an example of how to get a command called "CloseCommand" to execute when the window's Closed event is raised:
<Window x:Class="EventToCommand.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
Title="MainWindow" Height="300" Width="500">
<!-- Make sure to put this tag directly inside the Window,
and not inside a child element, since it is the Windows that has the Closed event -->
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closed">
<cmd:EventToCommand Command="{Binding CloseCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<!-- Windows contents -->
</Window>
To get access to the EventToCommand behaviour, you need to download MVVM Light Toolkit from the project downloads page , and then reference the following DLLs:
That is all that is needed.
Further instructions of how to get started with the toolkit can be found here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.