[WPF problems] Hide me! Not close
Zhou yinhui
A friend has encountered such a problem. In WPF, when closing a form. cancel = true, and then call the hide () method to hide the window rather than close it, but an exception is reported: "visibility cannot be set when window closing, or show () is called (), close (), hide () method ". OK. This article will help you solve the problem.
The key to the problem is that you can no longer call close in the closing method, so long as we know that the user intends to close the form, we only need to cancel the close in the closing method, then call hide in a method followed by closing. To reflect this "next method", I think of method queuing. For example, when methods in multiple threads use the same object, these methods will be queued; otherwise, an exception occurs. So we can use invoke to implement this queue.
Assume that Windows 2 of the window type is a window to be hidden. The window is hidden when you attempt to close the window. When you click btnshowwin2 in the main window, the window is displayed again.
We implement a delegate, and its proxy method will exception the form:Delegate Void Willhide ();
//
Private Willhide;
//
This . Willhide = New Willhide ( This . Hidewin2 );
//
Private Void Hidewin2 ()
{
This. Win2.hide ();
}
When closing is performed: Void Win2_closing ( Object Sender, canceleventargs E)
{
E. Cancel= True;
Dispatcher. begininvoke (system. Windows. Threading. dispatcherpriority. Normal,This. Willhide );
}
Everything is OK!
Overall Code : Code
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Using System. windows;
Using System. Windows. controls;
Using System. Windows. Data;
Using System. Windows. documents;
Using System. Windows. input;
Using System. Windows. Media;
Using System. Windows. Media. imaging;
Using System. Windows. Navigation;
Using System. Windows. shapes;
Using System. componentmodel;
Namespace Closingdemo
{
/**/ /// <Summary>
///Interaction logic for window1.xaml
/// </Summary>
Public Partial Class Window1: Window
{
Delegate Void Willhide ();
Private Window2 win2 = New Window2 ();
Private Willhide;
Public Window1 ()
{
Initializecomponent ();
Test ();
}
Private Void Hidewin2 ()
{
This. Win2.hide ();
}
Private Void Test ()
{
App. Current. mainwindow = This ;
App. Current. shutdownmode = Shutdownmode. onmainwindowclose;
This . Willhide = New Willhide ( This . Hidewin2 );
This . Win2.closing + = New Canceleventhandler (win2_closing );
This . Btnshowwin2.click + = New Routedeventhandler (btnshowwin2_click );
This . Win2.show ();
}
Void Btnshowwin2_click ( Object Sender, routedeventargs E)
{
This. Win2.show ();
}
Void Win2_closing ( Object Sender, canceleventargs E)
{
E. Cancel= True;
Dispatcher. begininvoke (system. Windows. Threading. dispatcherpriority. Normal,This. Willhide );
}
}
}