Thursday, April 12, 2012

ShowDialog in Closing-Event

If the user closes the Application a Save-File-Message have to be shown (to be sure that he wants to discard the changes of edited files).



to implement this, i have a menuitem with a command-binding (without key-gesture):



private void Command_Exit(object sender, ExecutedRoutedEventArgs e)
{
Application.Current.Shutdown();
}


the mainwindow has a closing-event. in this event i check if there unsaved files. if yes, the savedialog has to be opened (to choose, which files have to be saved):



private void Window_Closing(object sender, CancelEventArgs e)
{
if (sdl.Count() > 0)
{
SaveDialog sd = new SaveDialog();
IEnumerable<Doc> close = sd.ShowDialog(this);
if (close == null)
e.Cancel = true;
else
foreach (Doc document in close)
document.Save();
}

}


in this ShowDialog-Method (implemented in my SaveDialog-Class) i call



bool? ret = ShowDialog();
if (!ret.HasValue)
return null;
if (!ret.Value)
return null;


The problem is:



If i use the Alt+F4-Shortcut to close the Application (default-behaviour of the mainwindow) it works and i get the savedialog if there are unsaved files. but if i close the application by executing the Command_Exit-Method, the Method-Call



bool? ret = ShowDialog(); 


returns null and the dialog does not appear.



If i assign the Alt+F4 KeyGesture to the CommandBinding, the problem is switched: Executing Command_Exit works well but Alt+F4 Shortcut not.



What is the reason that the ShowDialog()-Method works not in both cases and how to fix it?





No comments:

Post a Comment