Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a New Frame Window From MainPage in Windows 10 Universal App?

How to open a new frame window which contains another xaml page when I click a button from the main window in universal app?

like image 771
Brajesh Kokkonda Avatar asked Sep 21 '15 10:09

Brajesh Kokkonda


1 Answers

You can check out a sample on how to do this from the Offical Microsoft Samples on GitHub as can be found here but I'll summarize quickly here. Another simpler implementation can be found on Mike Taulty's Blog.

Since you haven't specified a development language I will assume C# and XAML.

Create your button in XAML which will be clicked to create a new window:

<Button  
Content="Create"  
HorizontalAlignment="Center"  
VerticalAlignment="Center"  
Click="OnCreate" />

In the code behind, add your OnCreate click handler:

async void OnCreate(object sender, RoutedEventArgs e)  
{  
  CoreApplicationView newCoreView = CoreApplication.CreateNewView();  

  ApplicationView newAppView = null;  
  int mainViewId = ApplicationView.GetApplicationViewIdForWindow(  
    CoreApplication.MainView.CoreWindow);  

  await newCoreView.Dispatcher.RunAsync(  
    CoreDispatcherPriority.Normal,  
    () =>  
    {  
      newAppView = ApplicationView.GetForCurrentView();  
      Window.Current.Content = new SubWindowUserControl();  
      Window.Current.Activate();  
    });  

  await ApplicationViewSwitcher.TryShowAsStandaloneAsync(  
    newAppView.Id,  
    ViewSizePreference.UseHalf,  
    mainViewId,  
    ViewSizePreference.UseHalf);  
}

This creates a new window, and fetches the application view ID of your original window for you to reference. It then awaits a dispatched thread to run (in the UI thread of the new window) to get the new view the window contains which it adds a new SubWindowUserControl to, programatically, and is then activated (you MUST remember to do this). The new window is then shown in a new standalone window using some standard parameters.

Check out the API documentation here for more details on the ApplicationViewSwitcher class.

To take this code and make it show a new XAML page you can create your new page and change the async task running on the new window in the OnCreate code as follows:

  await newCoreView.Dispatcher.RunAsync(  
    CoreDispatcherPriority.Normal,  
    () =>  
    {  
      newAppView = ApplicationView.GetForCurrentView();  
      Window.Current.Content = new Frame();
      (Window.Current.Content as Frame).Navigate(typeof(<your_page>));
      Window.Current.Activate();  
    });  

This, instead of showing a new custom XAML element as its content, creates a new Frame which is then navigated to show your XAML page.

Hello Second Window!

Hope this helps!

like image 88
rcbevans Avatar answered Oct 22 '22 14:10

rcbevans