In a viewModel of my MVVM based WPF application, I have a two commands to handle two different Cancel clicks, at two different states.
- When there is no ongoing operation progress - it relays the
view.close()
method. - When progress is ongoing - it relays a
cancelWaiting = true
to the progress callback, which then accordingly pauses the progress while it pulls up a cancel confirmation message box and depending on yes/no either cancels or continues.
Both these commands have canExecute properties which resolve accordingly as per the two states.
I created a new method (in the same viewModel) which encapsulates these two commands. Now, I need to call this method when the global "X" close button is clicked. I tried the following:
Closing += (sender, e) => viewModel.CloseWindowCommand();
This resulted in an unhandled exception:
Cannot set Visibility to Visible or call Show, ShowDialog, Close, or WindowInteropHelper.EnsureHandle while a Window is closing.
with the call stack as:
at System.Windows.Window.VerifyNotClosing()
at System.Windows.Window.InternalClose(Boolean shutdown, Boolean ignoreCancel)
at System.Windows.Window.Close()
at Myapp.ViewModel.RootViewModel.<get_CloseCommand>b__0()
at Myapp.RelayCommand.Execute(Object parameter)
at Myapp.ViewModel.RootViewModel.CloseWindowCommand()
at Myapp.View.RootView.WindowClose(Object sender, CancelEventArgs e)
at System.Windows.Window.OnClosing(CancelEventArgs e)
at System.Windows.Window.WmClose()
at System.Windows.Window.WindowFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.PublicHooksFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
What am I doing wrong?
I have looked at a few related questions and posts (here, here) but I have been unable to locate the problem so far.
Any pointers are appreciated.