简体   繁体   中英

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

当我从通用应用程序主窗口中单击按钮时,如何打开一个包含另一个xaml页面的新框架窗口?

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.

您好第二个窗口!

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM