none
Opening a new window in the program from Windows Template Studio (unregistered in ShellPage). RRS feed

  • Question

  • When using Windows Template Studio (WPS), there was a problem with opening unregistered new windows.
    If you use WPS, you know about the automatic creation of the ShellPage where all windows are written as follows:

    <winui:NavigationView.MenuItems>
    
    <winui:NavigationViewItem x:Uid="Shell_MainWindow" Icon="Document" helpers:NavHelper.NavigateTo="views:MainWindowPage" />
    
    <winui:NavigationViewItem x:Uid="Shell_NewWindow" Icon="Document" helpers:NavHelper.NavigateTo="views:NewWindowPage" />
    
    <winui:NavigationViewItem x:Uid="Shell_NewWindow1" Icon="Document" helpers:NavHelper.NavigateTo="views:NewWindow1Page" />
    
    <winui:NavigationViewItem x:Uid="Shell_NewWindow2" Icon="Document" helpers:NavHelper.NavigateTo="views:NewWindow2Page" />
    
    ................. etc.
    
    </winui:NavigationView.MenuItems>

    but what if you need to open a window that is not in the ShellPage navigation?

    In VS, I created a new page and named it (for example) MyTablesPage

    According to an example from Windows-universal-samples -> Samples -> AppWindow.
    In the registered page (for example, in the above NewWindow2Page) created a CommandBar, created the Click = "AppBarButton_Click_3" event. Next, in the class NewWindow2Page, I registered the following lines:

    public sealed partial class NewWindow2Page : Page    
    {
        public NewWindow2ViewModel ViewModel { get; } = new NewWindow2Model();
    
        private AppWindow appWindow; 
        private Frame appWinFrame = new Frame();
    
        public NewWindow2Page()
        {
          InitializeComponent();
        }
    
        private async void AppBarButton_Click_3(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
           if(appWindow == null)
           {
           appWindow = await AppWindow.TryCreateAsync();
           appWindow.Closed += delegate { appWindow = null; 
           appWinFrame.Content = null;
           };
         appWinFrame.Navigate(typeof(MyTablesPage));
         ElementCompositionPreview.SetAppWindowContent(appWindow, appWinFrame);
        }
    
        await appWindow.TryShowAsync();
    }
    The application itself compiles, but when you click on the button in the CommandBar, the program crashes. What could be the reason?

    Tuesday, February 18, 2020 6:20 PM