Search code examples
xamlwinui-3

How to close a page.xaml in WinUI 3 by clicking the close button


I have a program with WinUI 3 that Includes MainWindow.xaml and a Page1.xaml, I have a Button on the MainWindow, clicking on it Causes Page1 to Open and load Correctly, Now I have a Close Button on Page1 That I Want to be Able to Close Page1 by Clicking this Button. There Is no Method Like This.Close or Unload For the Page Object. Do You Have a Solution? Please See the Picture


Update: Note that Page1 is Loaded as a Pop-up by ContentDialog, But Actually Page1 is not Loaded in the Frame.

pic

Why is there really no simple solution? ( Microsoft )


Solution

  • I'd use an event for this. It should look something like this:

    Page1.xaml

    <Page
        x:Class="TestApp.Page1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="using:TestApp"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
        mc:Ignorable="d">
    
        <StackPanel>
            <TextBlock Text="Page 1" />
            <Button
                Click="CloseButton_Click"
                Content="Close" />
        </StackPanel>
    
    </Page>
    

    Page1.xaml.cs

    using Microsoft.UI.Xaml;
    using Microsoft.UI.Xaml.Controls;
    using System;
    
    namespace TestApp;
    
    public sealed partial class Page1 : Page
    {
        public Page1()
        {
            this.InitializeComponent();
        }
    
        public event EventHandler? CloseRequested;
    
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            CloseRequested?.Invoke(this, EventArgs.Empty);
        }
    }
    

    and your ContentDialog:

    ContentDialog dialog = new();
    dialog.XamlRoot = this.XamlRoot;
    
    Page1 page = new();
    page.CloseRequested += (s, e) => dialog.Hide();
    dialog.Content = page;
    
    ContentDialogResult result = await dialog.ShowAsync();