UWP: Open a Page as New Window

Posted by Blake on 2/6/2019
)

The following snippet of code will allow you to open a Page as new window in a Universal Windows app (UWP).

/// <summary>
/// Opens a page given the page type as a new window.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
private async Task<bool> OpenPageAsWindowAsync(Type t)
{
    var view = CoreApplication.CreateNewView();
    int id = 0;

    await view.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        var frame = new Frame();
        frame.Navigate(t, null);                
        Window.Current.Content = frame;
        Window.Current.Activate();
        id = ApplicationView.GetForCurrentView().Id;
    });

    return await ApplicationViewSwitcher.TryShowAsStandaloneAsync(id);
}

To call this code from a button click event it would look something like the below. This assumes that I have a "Page" named "Settings".

private async void ButtonSettingsAsync_Click(object sender, RoutedEventArgs e)
{
    await OpenPageAsWindowAsync(typeof(Settings));
}