Vaya, parece que hay un montón de código aquí para esto. Stas arriba tenía el enfoque correcto para un mínimo esfuerzo. Aquí está mi adaptación (usando MVVMLight pero debería ser reconocible) ...Oh y el PassEventArgsToCommand = "Verdadero" es definitivamente necesario como se indicó anteriormente.
(crédito a Laurent Bugnion http://blog.galasoft.ch/archive/2009/10/18/clean-shutdown-in-silverlight-and-wpf-applications.aspx)
... MainWindow Xaml
...
WindowStyle="ThreeDBorderWindow"
WindowStartupLocation="Manual">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<cmd:EventToCommand Command="{Binding WindowClosingCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
En el modelo de vista:
///<summary>
/// public RelayCommand<CancelEventArgs> WindowClosingCommand
///</summary>
public RelayCommand<CancelEventArgs> WindowClosingCommand { get; private set; }
...
...
...
// Window Closing
WindowClosingCommand = new RelayCommand<CancelEventArgs>((args) =>
{
ShutdownService.MainWindowClosing(args);
},
(args) => CanShutdown);
en el ShutdownService
/// <summary>
/// ask the application to shutdown
/// </summary>
public static void MainWindowClosing(CancelEventArgs e)
{
e.Cancel = true; /// CANCEL THE CLOSE - let the shutdown service decide what to do with the shutdown request
RequestShutdown();
}
RequestShutdown se ve algo como lo siguiente, pero basicallyRequestShutdown o lo que sea se nombra decide si apagar el a plicación o no (que se cerrará la ventana alegremente de todos modos):
...
...
...
/// <summary>
/// ask the application to shutdown
/// </summary>
public static void RequestShutdown()
{
// Unless one of the listeners aborted the shutdown, we proceed. If they abort the shutdown, they are responsible for restarting it too.
var shouldAbortShutdown = false;
Logger.InfoFormat("Application starting shutdown at {0}...", DateTime.Now);
var msg = new NotificationMessageAction<bool>(
Notifications.ConfirmShutdown,
shouldAbort => shouldAbortShutdown |= shouldAbort);
// recipients should answer either true or false with msg.execute(true) etc.
Messenger.Default.Send(msg, Notifications.ConfirmShutdown);
if (!shouldAbortShutdown)
{
// This time it is for real
Messenger.Default.Send(new NotificationMessage(Notifications.NotifyShutdown),
Notifications.NotifyShutdown);
Logger.InfoFormat("Application has shutdown at {0}", DateTime.Now);
Application.Current.Shutdown();
}
else
Logger.InfoFormat("Application shutdown aborted at {0}", DateTime.Now);
}
}
También está interesado en una buena respuesta para responder a esto. – Sekhat
Descargué el código de Codeplex y lo depuré revelé: "No se pudo convertir el objeto del tipo 'System.ComponentModel.CancelEventArgs' para escribir 'System.Windows.RoutedEventArgs'." Funciona bien si ** no ** quiere el CancelEventArgs pero eso no responde a su pregunta ... –
Supongo que su código no funciona porque el control al que conectó su desencadenador no funciona tener un evento de cierre. Su contexto de datos no es una ventana ... Probablemente es una plantilla de datos con una cuadrícula o algo así, que no tiene un evento de Cierre. Entonces la respuesta de dbkk es la mejor respuesta en este caso. Sin embargo, prefiero el enfoque Interaction/EventTrigger cuando el evento está disponible. – NielW