UWP page life cycle

I have a multiple page application related to navigation logic.

One of the pages contains a webcam-bound media element. After entering the background (for example, minimizing the menu with a click of the application mouse), the camera element stopped. So I subscribe to the
Windows.ApplicationModel.Core.CoreApplication.LeavingBackground event and re-initialize the camera. It's okay if the current page is a page with this subscription and a camera element. If the current page is a different page and the application is restored, the LeavingBackground event fires anyway, so the hidden page tries to re-initialize the camera.

I tried setting this.NavigationCacheMode = NavigationCacheMode.Disabled, so the page instance containing the media item and subscribing to the LeavingBackground event should in theory be removed after the NavigatedTo event according to MSDN. But this works in a different way, which I don't understand.

It seems that the camera page was created once and always and will always receive the LeavingBackgound event - which is bad for me.

I tried to compare Window.Current.Content.GetType () with the type of the page that contains the camera element, but sometimes that type contains the type of other pages, but sometimes it is offset from Content.Content, so I'm stuck.

+3


source to share


2 answers


I would suggest that you need to unregister the event handler when navigating from this page:



public sealed partial class WebCamPage
{
    public WebCamPage()
    {
        InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        Windows.ApplicationModel.Core.CoreApplication.LeavingBackground += OnLeavingBackground;
    }

    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
        Windows.ApplicationModel.Core.CoreApplication.LeavingBackground -= OnLeavingBackground;
    }

    private void OnLeavingBackground(object sender, LeavingBackgroundEventArgs e)
    {
        // Your code here.
    }
}

      

+3


source


You need to handle the pause and resume events to properly clear and re-initialize the camera, as shown in the sample camera app:

https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/CameraStarterKit/cs/MainPage.xaml.cs



Thank you Stefan Wick - Windows Developer Platform

+1


source







All Articles