public async Task NavigateToCurrentViewModel_Calls_VieModel_OnNavigatedTo()
        {
            await ExecuteOnUIThread(() =>
            {
                var frame = new FrameFacadeAdapter(new Frame());

                bool viewModelNavigatedToCalled = false;
                var viewModel = new MockPageViewModel();
                viewModel.OnNavigatedFromCommand = (a, b) => Assert.IsTrue(true);
                viewModel.OnNavigatedToCommand = (parameter, navigationMode, frameState) =>
                {
                    Assert.AreEqual(NavigationMode.New, navigationMode);
                    viewModelNavigatedToCalled = true;
                };

                // Set up the viewModel to the Page we navigated
                frame.Navigated += (sender, e) =>
                {
                    var view = frame.Content as FrameworkElement;
                    view.DataContext = viewModel;
                };

                var sessionStateService = new MockSessionStateService();
                sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();

                var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);

                navigationService.Navigate("Mock", 1);

                Assert.IsTrue(viewModelNavigatedToCalled);
            });
        }
Exemplo n.º 2
0
        /// <summary>
        /// Invoked when this page will no longer be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached. The Parameter
        /// property provides the group to be displayed.</param>
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            var frameFacade = new FrameFacadeAdapter(this.Frame);
            var frameState  = GetSessionStateForFrame(frameFacade);
            var pageState   = new Dictionary <String, Object>();

            this.SaveState(pageState);
            frameState[_pageKey] = pageState;
        }
        public async Task Navigate_To_Invalid_Page()
        {
            await ExecuteOnUIThread(() =>
            {
                var frame = new FrameFacadeAdapter(new Frame());
                var sessionStateService = new MockSessionStateService();
                sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();

                var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(string), sessionStateService);

                bool result = navigationService.Navigate("Mock", 1);

                Assert.IsFalse(result);
                Assert.IsNull(frame.Content);
            });
        }
        public async Task Navigate_To_Valid_Page()
        {
            await ExecuteOnUIThread(() =>
            {
                var frame = new FrameFacadeAdapter(new Frame());
                var sessionStateService = new MockSessionStateService();
                sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
                var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);

                bool result = navigationService.Navigate("Mock", 1);

                Assert.IsTrue(result);
                Assert.IsNotNull(frame.Content);
                Assert.IsInstanceOfType(frame.Content, typeof(MockPage));
                Assert.AreEqual(1, ((MockPage)frame.Content).PageParameter);
            });
        }
Exemplo n.º 5
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="navigationEventArgs">Event data that describes how this page was reached. The Parameter
        /// property provides the group to be displayed.</param>
        protected override void OnNavigatedTo(NavigationEventArgs navigationEventArgs)
        {
            if (navigationEventArgs == null)
            {
                throw new ArgumentNullException(nameof(navigationEventArgs));
            }

            // Returning to a cached page through navigation shouldn't trigger state loading
            if (_pageKey != null)
            {
                return;
            }

            var frameFacade = new FrameFacadeAdapter(Frame);
            var frameState  = GetSessionStateForFrame(frameFacade);

            _pageKey = "Page-" + frameFacade.BackStackDepth;

            if (navigationEventArgs.NavigationMode == NavigationMode.New)
            {
                // Clear existing state for forward navigation when adding a new page to the
                // navigation stack
                var nextPageKey   = _pageKey;
                int nextPageIndex = frameFacade.BackStackDepth;
                while (frameState.Remove(nextPageKey))
                {
                    nextPageIndex++;
                    nextPageKey = "Page-" + nextPageIndex;
                }

                // Pass the navigation parameter to the new page
                LoadState(navigationEventArgs.Parameter, null);
            }
            else
            {
                // Pass the navigation parameter and preserved page state to the page, using
                // the same strategy for loading suspended state and recreating pages discarded
                // from cache
                LoadState(navigationEventArgs.Parameter, (Dictionary <String, Object>)frameState[_pageKey]);
            }
        }
        public async Task PageTokenThatCannotBeResolved_ThrowsMeaningfulException()
        {
            await ExecuteOnUIThread(() =>
            {
                var frame = new FrameFacadeAdapter(new Frame());
                var sessionStateService = new MockSessionStateService();
                var frameSessionState = new Dictionary<string, object>();
                sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => frameSessionState;

                Func<string, Type> unresolvablePageTokenReturnsNull = pageToken => null;
                var navigationService = new FrameNavigationService(frame, unresolvablePageTokenReturnsNull, sessionStateService);

                Assert.ThrowsException<ArgumentException>(
                    () =>   navigationService.Navigate("anything", 1)
                    );

            });
        }
        public async Task RestoreSavedNavigation_ClearsOldForwardNavigation()
        {
            await ExecuteOnUIThread(() =>
            {
                var frame = new FrameFacadeAdapter(new Frame());
                var sessionStateService = new MockSessionStateService();
                var frameSessionState = new Dictionary<string, object>();
                sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => frameSessionState;
                var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPageWithViewModel), sessionStateService);

                navigationService.Navigate("Page1", 1);
                Assert.AreEqual(1, frameSessionState.Count, "VM 1 state only");

                navigationService.Navigate("Page2", 2);
                Assert.AreEqual(2, frameSessionState.Count, "VM 1 and 2");

                navigationService.Navigate("Page3", 3);
                Assert.AreEqual(3, frameSessionState.Count, "VM 1, 2, and 3");

                navigationService.GoBack();
                Assert.AreEqual(2, ((Dictionary<string, object>)frameSessionState["ViewModel-2"]).Count);
                Assert.AreEqual(3, frameSessionState.Count, "VM 1, 2, and 3");

                navigationService.Navigate("Page4", 4);
                Assert.AreEqual(0, ((Dictionary<string,object>)frameSessionState["ViewModel-2"]).Count);
                Assert.AreEqual(3, frameSessionState.Count, "VM 1, 2, and 4");
            });
        }
        public async Task ViewModelOnNavigatedFromCalled_WithItsOwnStateDictionary()
        {
            await ExecuteOnUIThread(() =>
            {
                var frame = new FrameFacadeAdapter(new Frame());
                var sessionStateService = new MockSessionStateService();
                var frameSessionState = new Dictionary<string, object>();
                sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => frameSessionState;
                var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPageWithViewModel), sessionStateService);

                navigationService.Navigate("Page1", 1);
                Assert.AreEqual(1, frameSessionState.Count, "VM 1 state only");

                navigationService.Navigate("Page2", 2);
                Assert.AreEqual(2, frameSessionState.Count, "VM 1 and 2");

                navigationService.Navigate("Page1", 1);
                Assert.AreEqual(3, frameSessionState.Count, "VM 1, 2, and 1 again.");

                navigationService.Navigate("Page3", 3);
                Assert.AreEqual(4, frameSessionState.Count, "VM 1, 2, 1, and 3");
            });
        }
        public async Task GoBack_When_CanGoBack()
        {
            await ExecuteOnUIThread(() =>
            {
                var frame = new FrameFacadeAdapter(new Frame());
                var sessionStateService = new MockSessionStateService();
                sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
                var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);

                bool resultFirstNavigation = navigationService.Navigate("MockPage", 1);

                Assert.IsInstanceOfType(frame.Content, typeof(MockPage));
                Assert.AreEqual(1, ((MockPage)frame.Content).PageParameter);
                Assert.IsFalse(navigationService.CanGoBack());

                bool resultSecondNavigation = navigationService.Navigate("Mock", 2);

                Assert.IsInstanceOfType(frame.Content, typeof(MockPage));
                Assert.AreEqual(2, ((MockPage)frame.Content).PageParameter);
                Assert.IsTrue(navigationService.CanGoBack());

                navigationService.GoBack();

                Assert.IsInstanceOfType(frame.Content, typeof(MockPage));
                Assert.AreEqual(1, ((MockPage)frame.Content).PageParameter);
                Assert.IsFalse(navigationService.CanGoBack());
            });
        }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes the Frame and its content.
        /// </summary>
        /// <param name="args">The <see cref="IActivatedEventArgs"/> instance containing the event data.</param>
        /// <returns>A task of a Frame that holds the app content.</returns>
        protected async Task<Frame> InitializeFrameAsync(IActivatedEventArgs args)
        {
            var rootFrame = Window.Current.Content as Frame;
            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                if (ExtendedSplashScreenFactory != null)
                {
                    Page extendedSplashScreen = this.ExtendedSplashScreenFactory.Invoke(args.SplashScreen);
                    rootFrame.Content = extendedSplashScreen;
                }

                var frameFacade = new FrameFacadeAdapter(rootFrame);

                //Initialize PrismApplication common services
                SessionStateService = new SessionStateService();

                //Configure VisualStateAwarePage with the ability to get the session state for its frame
                VisualStateAwarePage.GetSessionStateForFrame =
                    frame => SessionStateService.GetSessionStateForFrame(frameFacade);

                //Associate the frame with a key
                SessionStateService.RegisterFrame(frameFacade, "AppFrame");

                NavigationService = CreateNavigationService(frameFacade, SessionStateService);

                if (ApiInformation.IsTypePresent("Windows.UI.ApplicationSettings.SettingsPane"))
                {
                    // TODO BL : keep an eye on MSDN for future SDK release updates on SettingsPane
#pragma warning disable CS0618 // Type or member is obsolete // Still marked on MSDN as a valid type for the Windows family
                    SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;
#pragma warning restore CS0618
                }
                // Register hardware back button event if present
                if (ApiInformation.IsEventPresent("Windows.Phone.UI.Input.HardwareButtons", "BackPressed"))
                {
                    HardwareButtons.BackPressed += HardwareButtonsOnBackPressed;
                }

                // Set a factory for the ViewModelLocator to use the default resolution mechanism to construct view models
                ViewModelLocationProvider.SetDefaultViewModelFactory(Resolve);

                OnRegisterKnownTypesForSerialization();
                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    await SessionStateService.RestoreSessionStateAsync();
                }

                await OnInitializeAsync(args);
                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state and navigate to the last page visited
                    try
                    {
                        SessionStateService.RestoreFrameState();
                        NavigationService.RestoreSavedNavigation();
                        _isRestoringFromTermination = true;
                    }
                    catch (SessionStateServiceException)
                    {
                        // Something went wrong restoring state.
                        // Assume there is no state and continue
                    }
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            return rootFrame;
        }
        public async Task Suspending_Calls_VieModel_OnNavigatedFrom()
        {
            await ExecuteOnUIThread(() =>
            {
                var frame = new FrameFacadeAdapter(new Frame());
                var sessionStateService = new MockSessionStateService();
                sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
                var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);

                navigationService.Navigate("Mock", 1);

                var viewModel = new MockPageViewModel();
                viewModel.OnNavigatedFromCommand = (frameState, suspending) =>
                {
                    Assert.IsTrue(suspending);
                };

                var page = (MockPage)frame.Content;
                page.DataContext = viewModel;

                navigationService.Suspending();
            });
        }
Exemplo n.º 12
0
        /// <summary>
        /// Initializes the Frame and its content.
        /// </summary>
        /// <param name="args">The <see cref="IActivatedEventArgs"/> instance containing the event data.</param>
        /// <returns>A task of a Frame that holds the app content.</returns>
        protected async Task<Frame> InitializeFrameAsync(IActivatedEventArgs args)
        {
            // Create a Frame to act as the navigation context and navigate to the first page
            var rootFrame = new Frame();

            if (ExtendedSplashScreenFactory != null)
            {
                Page extendedSplashScreen = this.ExtendedSplashScreenFactory.Invoke(args.SplashScreen);
                rootFrame.Content = extendedSplashScreen;
            }

            rootFrame.Navigated += OnNavigated;

            var frameFacade = new FrameFacadeAdapter(rootFrame);

            //Initialize PrismApplication common services
            SessionStateService = new SessionStateService();

            //Configure VisualStateAwarePage with the ability to get the session state for its frame
            VisualStateAwarePage.GetSessionStateForFrame =
                frame => SessionStateService.GetSessionStateForFrame(frameFacade);

            //Associate the frame with a key
            SessionStateService.RegisterFrame(frameFacade, "AppFrame");

            NavigationService = CreateNavigationService(frameFacade, SessionStateService);

            DeviceGestureService = CreateDeviceGestureService();
            DeviceGestureService.InitializeEventHandlers();
            DeviceGestureService.GoBackRequested += OnGoBackRequested;
            DeviceGestureService.GoForwardRequested += OnGoForwardRequested;

            // Set a factory for the ViewModelLocator to use the default resolution mechanism to construct view models
            ViewModelLocationProvider.SetDefaultViewModelFactory(Resolve);

            OnRegisterKnownTypesForSerialization();
            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                await SessionStateService.RestoreSessionStateAsync();
            }

            await OnInitializeAsync(args);

            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                // Restore the saved session state and navigate to the last page visited
                try
                {
                    SessionStateService.RestoreFrameState();
                    NavigationService.RestoreSavedNavigation();
                    _isRestoringFromTermination = true;
                }
                catch (SessionStateServiceException)
                {
                    // Something went wrong restoring state.
                    // Assume there is no state and continue
                }
            }

            return rootFrame;
        }
Exemplo n.º 13
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached. The Parameter
        /// property provides the group to be displayed.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e == null) throw new ArgumentNullException("e");

            // Returning to a cached page through navigation shouldn't trigger state loading
            if (this._pageKey != null) return;

            var frameFacade = new FrameFacadeAdapter(this.Frame);
            var frameState = GetSessionStateForFrame(frameFacade);
            this._pageKey = "Page-" + frameFacade.BackStackDepth;

            if (e.NavigationMode == NavigationMode.New)
            {
                // Clear existing state for forward navigation when adding a new page to the
                // navigation stack
                var nextPageKey = this._pageKey;
                int nextPageIndex = frameFacade.BackStackDepth;
                while (frameState.Remove(nextPageKey))
                {
                    nextPageIndex++;
                    nextPageKey = "Page-" + nextPageIndex;
                }

                // Pass the navigation parameter to the new page
                this.LoadState(e.Parameter, null);
            }
            else
            {
                // Pass the navigation parameter and preserved page state to the page, using
                // the same strategy for loading suspended state and recreating pages discarded
                // from cache
                this.LoadState(e.Parameter, (Dictionary<String, Object>)frameState[this._pageKey]);
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// Invoked when this page will no longer be displayed in a Frame.
 /// </summary>
 /// <param name="e">Event data that describes how this page was reached. The Parameter
 /// property provides the group to be displayed.</param>
 protected override void OnNavigatedFrom(NavigationEventArgs e)
 {
     var frameFacade = new FrameFacadeAdapter(this.Frame);
     var frameState = GetSessionStateForFrame(frameFacade);
     var pageState = new Dictionary<String, Object>();
     this.SaveState(pageState);
     frameState[_pageKey] = pageState;
 }
        public async Task Resuming_Calls_ViewModel_OnNavigatedTo()
        {
            await ExecuteOnUIThread(() =>
            {
                var frame = new FrameFacadeAdapter(new Frame());
                var sessionStateService = new MockSessionStateService();
                sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
                var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);

                navigationService.Navigate("Mock", 1);

                var viewModel = new MockPageViewModel();
                viewModel.OnNavigatedToCommand = (navigationParameter, navigationMode, frameState) =>
                {
                    Assert.AreEqual(NavigationMode.Refresh, navigationMode);
                };

                var page = (MockPage)frame.Content;
                page.DataContext = viewModel;

                navigationService.RestoreSavedNavigation();
            });
        }
        public async Task NavigateFromCurrentViewModel_Calls_VieModel_OnNavigatedFrom()
        {
            await ExecuteOnUIThread(() =>
            {
                var frame = new FrameFacadeAdapter(new Frame());

                bool viewModelNavigatedFromCalled = false;
                var viewModel = new MockPageViewModel();
                viewModel.OnNavigatedFromCommand = (frameState, suspending) =>
                {
                    Assert.IsFalse(suspending);
                    viewModelNavigatedFromCalled = true;
                };

                var sessionStateService = new MockSessionStateService();
                sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();

                var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);

                // Initial navigatio
                navigationService.Navigate("page0", 0);

                // Set up the frame's content with a Page
                var view = new MockPage();
                view.DataContext = viewModel;
                frame.Content = view;

                // Navigate to fire the NavigatedToCurrentViewModel
                navigationService.Navigate("page1", 1);

                Assert.IsTrue(viewModelNavigatedFromCalled);
            });
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes the Frame and its content.
        /// </summary>
        /// <param name="args">The <see cref="IActivatedEventArgs"/> instance containing the event data.</param>
        /// <returns>A task of a Frame that holds the app content.</returns>
        protected async Task<Frame> InitializeFrameAsync(IActivatedEventArgs args)
        {
            var rootFrame = Window.Current.Content as Frame;
            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                if (ExtendedSplashScreenFactory != null)
                {
                    Page extendedSplashScreen = this.ExtendedSplashScreenFactory.Invoke(args.SplashScreen);
                    rootFrame.Content = extendedSplashScreen;
                }

                var frameFacade = new FrameFacadeAdapter(rootFrame);

                //Initialize PrismApplication common services
                SessionStateService = new SessionStateService();

                //Configure VisualStateAwarePage with the ability to get the session state for its frame
                VisualStateAwarePage.GetSessionStateForFrame =
                    frame => SessionStateService.GetSessionStateForFrame(frameFacade);

                //Associate the frame with a key
                SessionStateService.RegisterFrame(frameFacade, "AppFrame");

                NavigationService = CreateNavigationService(frameFacade, SessionStateService);
                //TODO: BDN Figure out what to do about settings pane stuff
                //SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;

                // Set a factory for the ViewModelLocator to use the default resolution mechanism to construct view models
                ViewModelLocationProvider.SetDefaultViewModelFactory(Resolve);

                OnRegisterKnownTypesForSerialization();
                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    await SessionStateService.RestoreSessionStateAsync();
                }

                OnInitialize(args);
                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state and navigate to the last page visited
                    try
                    {
                        SessionStateService.RestoreFrameState();
                        NavigationService.RestoreSavedNavigation();
                        _isRestoringFromTermination = true;
                    }
                    catch (SessionStateServiceException)
                    {
                        // Something went wrong restoring state.
                        // Assume there is no state and continue
                    }
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            return rootFrame;
        }