Search code examples
c#uwptemplate10

What should the value of Windows.Current.Content be after opening a secondary window?


This is the suggested code in the App class from the Template10 article on implementing a shell:

public override Task OnInitializeAsync(IActivatedEventArgs args)
{
    var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);
    Window.Current.Content = new Views.Shell(nav);
    return Task.FromResult<object>(null);
}

The new shell object is assigned to Windows.Current.Content.

This is the suggested code for opening a secondary window (not with a shell), from the Template10 Secondary window example code:

 var control = await NavigationService.OpenAsync(typeof(MySecondaryPage), null, Guid.NewGuid().ToString());  

                control.Released += Control_Released;

What is the relationship between Windows.Current.Content and the secondary window?


Solution

  • What is the relationship between Windows.Current.Content and the secondary window?

    Actually, The NavigationService.OpenAsync method internally invoke ViewService.OpenAsync.

    public async Task<IViewLifetimeControl> OpenAsync(UIElement content, string title = null,
        ViewSizePreference size = ViewSizePreference.UseHalf)
    {
        this.Log($"Frame: {content}, Title: {title}, Size: {size}");
    
        var currentView = ApplicationView.GetForCurrentView();
        title = title ?? currentView.Title;
    
        var newView = CoreApplication.CreateNewView();
        var dispatcher = DispatcherEx.Create(newView.Dispatcher);
        var newControl = await dispatcher.Dispatch(async () =>
        {
            var control = ViewLifetimeControl.GetForCurrentView();
            var newWindow = Window.Current;
            var newAppView = ApplicationView.GetForCurrentView();
            newAppView.Title = title;
    
            // TODO: (Jerry)
            // control.NavigationService = nav;
    
            newWindow.Content = content;
            newWindow.Activate();
    
            await ApplicationViewSwitcher
                .TryShowAsStandaloneAsync(newAppView.Id, ViewSizePreference.Default, currentView.Id, size);
            return control;
        }).ConfigureAwait(false);
        return newControl;
    }
    

    From the above code, you could get the app's Window(Singleton) has not been changed, when the second window activated, the Content of Window was replaced with second page. And when the previous window activated the Windows.Current.Content will turn the fist page back. And you could verify this with Window.Current.Activated event.

    Window.Current.Activated += Current_Activated;
    
    private void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
    {
     // check the sender
    }