My app has multiple pages. When I press the Close key in the toolbar, how can I detect the OnClosing event in the single page to avoid closing the app instead of going back to the MainWindow with "this.Frame.GoBack();" ?
I can only catch OnClosing on MainWindow
CodePudding user response:
You can use the Unloaded
event on Pages
.
*.xaml
<local:TestPage Unloaded="TestPage_Unloaded" />
*.xaml.cs
private void TestPage_Unloaded(object sender, RoutedEventArgs e)
{
// Do your page closing work here...
}
CodePudding user response:
You could store a reference to the window in a property or field in your App.xaml.cs
class as suggested here and then handle the Closing
event of the window in the Page
class something like this:
public sealed partial class MainPage : Page
{
private Window _parentWindow;
public MainPage()
{
this.InitializeComponent();
this.Loaded = onl oaded;
this.Unloaded = OnUnloaded;
}
private void onl oaded(object sender, RoutedEventArgs e)
{
_parentWindow = (Application.Current as App)?.m_window;
if (_parentWindow != null)
_parentWindow.Closed = OnWindowClosed;
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
if (_parentWindow != null)
_parentWindow.Closed -= OnWindowClosed;
}
private void OnWindowClosed(object sender, WindowEventArgs args)
{
// Prevent the window from being closed based on some logic of yours...
args.Handled = true;
}
}