Beispiel #1
0
        private void AddHandler()
        {
            NavigatedEventHandler        successHandler = null;
            NavigationFailedEventHandler failureHandler = null;
            NavigatingCancelEventHandler beforeHandler  = null;

            successHandler = (s, e) =>
            {
                Frame.Navigated        -= successHandler;
                Frame.NavigationFailed -= failureHandler;

                AfterNavigation(null, e.Content as UserControl);
            };

            failureHandler = (s, e) =>
            {
                Frame.Navigated        -= successHandler;
                Frame.NavigationFailed -= failureHandler;

                AfterNavigation(e.Exception, null);
            };

            beforeHandler = (s, e) =>
            {
                Frame.Navigating -= beforeHandler;

                BeforeNavigation();
            };

            Frame.Navigated        += successHandler;
            Frame.NavigationFailed += failureHandler;
            Frame.Navigating       += beforeHandler;
        }
        public static bool Navigate <T>(this DependencyObject from, Uri to, Action <Frame, T> setParamsBlock = null) where T : class
        {
            var frame = from;

            if (!(frame is Frame))
            {
                frame = Application.Current.RootVisual;
            }
            var p = frame as Frame;

            if (setParamsBlock != null)
            {
                NavigatedEventHandler handle = null;
                handle = new NavigatedEventHandler((s, e) =>
                {
                    if (handle == null)
                    {
                        return;
                    }
                    if (e.Uri == to && e.NavigationMode == NavigationMode.New)
                    {
                        (!(handle == null || !(e.Content is T))).Assert("Navigate<" + typeof(T) + "> e.Content is " + e.Content);
                        setParamsBlock(p, e.Content as T);
                        p.Navigated -= handle;
                        handle       = null;
                    }
                });
                p.Navigated += handle;
            }
            return(p.Navigate(to));
        }
        private void NavigateBrowser(Button button, bool forward, WebBrowser browser = null)
        {
            browser = browser ?? button.CommandParameter as WebBrowser;
            var canNavigate = forward ? browser.CanGoForward : browser.CanGoBack;

            if (canNavigate)
            {
                button.IsEnabled = false;

                NavigatedEventHandler navigated = null;
                navigated = (s, a) =>
                {
                    browser.Navigated -= navigated;
                    button.IsEnabled   = true;
                };
                browser.Navigated += navigated;

                if (forward)
                {
                    browser.GoForward();
                }
                else
                {
                    browser.GoBack();
                }
            }
        }
 /// <summary>
 ///   Creates an instance of <see cref = "PhoneApplicationServiceAdapter" />.
 /// </summary>
 public PhoneApplicationServiceAdapter(Frame rootFrame)
 {
     service            = PhoneApplicationService.Current;
     service.Launching += delegate { isResurrecting = false; };
     service.Activated += delegate {
         if (isResurrecting)
         {
             Resurrecting();
             NavigatedEventHandler onNavigated = null;
             onNavigated = (s2, e2) => {
                 Resurrected();
                 rootFrame.Navigated -= onNavigated;
             };
             rootFrame.Navigated += onNavigated;
             isResurrecting       = false;
         }
         else
         {
             Continuing();
             NavigatedEventHandler onNavigated = null;
             onNavigated = (s2, e2) => {
                 Continued();
                 rootFrame.Navigated -= onNavigated;
             };
             rootFrame.Navigated += onNavigated;
         }
     };
 }
Beispiel #5
0
 /// <summary>
 ///   Creates an instance of <see cref = "PhoneApplicationServiceAdapter" />.
 /// </summary>
 public PhoneApplicationServiceAdapter(Frame rootFrame)
 {
     service            = PhoneApplicationService.Current;
     service.Activated += (sender, args) => {
         if (!args.IsApplicationInstancePreserved)
         {
             IsResurrecting = true;
             Resurrecting();
             NavigatedEventHandler onNavigated = null;
             onNavigated = (s2, e2) => {
                 IsResurrecting = false;
                 Resurrected();
                 rootFrame.Navigated -= onNavigated;
             };
             rootFrame.Navigated += onNavigated;
         }
         else
         {
             Continuing();
             NavigatedEventHandler onNavigated = null;
             onNavigated = (s2, e2) => {
                 Continued();
                 rootFrame.Navigated -= onNavigated;
             };
             rootFrame.Navigated += onNavigated;
         }
     };
 }
Beispiel #6
0
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// navigatedeventhandler.BeginInvoke(sender, e, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this NavigatedEventHandler navigatedeventhandler, Object sender, NavigationEventArgs e, AsyncCallback callback)
        {
            if (navigatedeventhandler == null)
            {
                throw new ArgumentNullException("navigatedeventhandler");
            }

            return(navigatedeventhandler.BeginInvoke(sender, e, callback, null));
        }
Beispiel #7
0
        /// <summary>
        /// Occurs when a previously tombstoned application instance is resurrected.
        /// </summary>
        protected virtual void OnActivate(object sender, ActivatedEventArgs e)
        {
            NavigatedEventHandler onNavigated = null;

            onNavigated = (s2, e2) => {
                Resurrect(SelectInstancesToResurrect());
                RootFrame.Navigated -= onNavigated;
            };
            RootFrame.Navigated += onNavigated;
        }
Beispiel #8
0
        /// <summary>
        /// Handles the Navigated event.
        /// </summary>
        /// <param name="viewModelToBind">ViewModel to be bound to the target view or null</param>
        private void SubscribeNavigatedHandler(NavigableViewModelBase viewModelToBind)
        {
            NavigatedEventHandler navigatedHandler = null;

            navigatedHandler = (sender, e) =>
            {
                _frame.Navigated -= navigatedHandler;
                HandleServiceNavigatedToContent(e, viewModelToBind);
            };

            _frame.Navigated += navigatedHandler;
        }
        public void OpenDetails(Event currentEvent)
        {
            navigatedHandler += (s, e) =>
                {
                    _navigationService.Navigated -= navigatedHandler;
                    _events.Publish(currentEvent);
                };

            _navigationService.Navigated += navigatedHandler;
            _navigationService.UriFor<EventDetailsViewModel>()
                .Navigate();
        }
        public static void NavigateToMain(this INavigationService service, string parameter)
        {
            NavigatedEventHandler handler = null;
            handler = (s, args) =>
            {
                service.Frame.Navigated -= handler;

                if (args.Content is MainPage page)
                {
                    page.Activate(parameter);
                }
            };

            service.Frame.Navigated += handler;
            service.Navigate(typeof(MainPage));
        }
Beispiel #11
0
        /// <summary>
        /// If we call SetTrigger in the Constructor, it won't affect to the UI, to make
        /// a call for the first time in the best place, it is in the Navigated Event of the Frame
        /// </summary>
        private void Initialize()
        {
            if (!DesignModeEnabled)
            {
                //Initial Trigger
                NavigatedEventHandler framenavigated = null;
                framenavigated = (s, e) =>
                {
                    DeviceInformation.DisplayFrame.Navigated -= framenavigated;
                    SetTrigger();
                };
                DeviceInformation.DisplayFrame.Navigated += framenavigated;

                //Orientation Trigger
                DeviceInformation.DisplayInformation.OrientationChanged += (s, e) => SetTrigger();
            }
        }
Beispiel #12
0
        /// <summary>
        /// Tells the activator that the application should expect requests for a particular type of Chooser.
        /// </summary>
        /// <typeparam name="TChooser">The type of chooser to handle request for.</typeparam>
        /// <typeparam name="TResult">The type of result returned by the chooser.</typeparam>
        public void InstallChooser <TChooser, TResult>()
            where TChooser : ChooserBase <TResult>, new()
            where TResult : TaskEventArgs
        {
            var manager = new ChooserManager <TChooser, TResult>(this, (IPhoneService)getInstance(typeof(IPhoneService)));

            taskManagers.Add(manager);

            var navService = (INavigationService)getInstance(typeof(INavigationService));
            NavigatedEventHandler handler = null;

            handler = (s, e) => {
                manager.PrepareToReceiveCallbacks();
                navService.Navigated -= handler;
            };
            navService.Navigated += handler;
        }
        public static void Navigate <TViewModel>(this NavigateHelper <TViewModel> uriBuilder, INavigationService navigationService, Action <TViewModel> action) where TViewModel : class
        {
            NavigatedEventHandler navigationServerOnNavigated = null;

            navigationServerOnNavigated = (s, e) =>
            {
                var viewModel = ViewModelLocator.LocateForView(e.Content) as TViewModel;
                if (viewModel != null)
                {
                    action(viewModel);
                }
                navigationService.Navigated -= navigationServerOnNavigated;
            };

            navigationService.Navigated += navigationServerOnNavigated;
            uriBuilder.Navigate();
        }
        public static bool Navigate <T>(this NavigationService from, Uri to, Action <NavigationService, T> setParamsBlock = null) where T : class
        {
            var p = from;

            if (setParamsBlock != null)
            {
                NavigatedEventHandler handle = null;
                handle = new NavigatedEventHandler((s, e) =>
                {
                    if (e.Uri == to && e.NavigationMode == NavigationMode.New)
                    {
                        setParamsBlock(p, e.Content as T);
                        p.Navigated -= handle;
                    }
                });
                p.Navigated += handle;
            }
            return(p.Navigate(to));
        }
Beispiel #15
0
        /// <summary>
        /// Raises the Navigated event synchronously.
        /// </summary>
        /// <param name="content">A reference to the object content that is being navigated to.</param>
        /// <param name="uri">A URI value representing the navigation content.</param>
        /// <param name="existingContentPage">The existing content cast to a Page</param>
        /// <param name="newContentPage">The new content cast to a Page</param>
        private void RaiseNavigated(object content, Uri uri, Page existingContentPage, Page newContentPage)
        {
            NavigatedEventHandler eventHandler = this.Navigated;

            if (eventHandler != null)
            {
                NavigationEventArgs eventArgs = new NavigationEventArgs(content, uri);
                eventHandler(this, eventArgs);
            }

            if (existingContentPage != null && content != null)
            {
                existingContentPage.InternalOnNavigatedFrom(new NavigationEventArgs(content, uri));
            }

            if (newContentPage != null)
            {
                newContentPage.InternalOnNavigatedTo(new NavigationEventArgs(content, uri));
            }
        }
Beispiel #16
0
 public static async Task NavigateAsync <T>(this Frame frame, bool clearHistory = false, Action <NavigationEventArgs> afterNavigated = null)
 {
     await frame.Dispatcher.RunAsync(global::Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
     {
         NavigatedEventHandler navigatedHandler = null;
         navigatedHandler = new NavigatedEventHandler(delegate(object sender, NavigationEventArgs args)
         {
             frame.Navigated -= navigatedHandler;
             if (clearHistory)
             {
                 frame.BackStack.Clear();
             }
             if (afterNavigated != null)
             {
                 afterNavigated(args);
             }
         });
         frame.Navigated += navigatedHandler;
         frame.Navigate(typeof(T));
     });
 }
Beispiel #17
0
        private void AddHandler()
        {
            NavigatedEventHandler        successHandler = null;
            NavigationFailedEventHandler failureHandler = null;

            successHandler = (s, e) =>
            {
                Frame.Navigated        -= successHandler;
                Frame.NavigationFailed -= failureHandler;

                AfterNavigation();
            };

            failureHandler = (s, e) =>
            {
                Frame.Navigated        -= successHandler;
                Frame.NavigationFailed -= failureHandler;

                AfterNavigation();
            };

            Frame.Navigated        += successHandler;
            Frame.NavigationFailed += failureHandler;
        }
        private void AddHandler()
        {
            NavigatedEventHandler        successHandler = null;
            NavigationFailedEventHandler failureHandler = null;

            successHandler = (s, e) =>
            {
                _rootFrame.Navigated        -= successHandler;
                _rootFrame.NavigationFailed -= failureHandler;

                AfterNavigation(null, e.Content as UserControl);
            };

            failureHandler = (s, e) =>
            {
                _rootFrame.Navigated        -= successHandler;
                _rootFrame.NavigationFailed -= failureHandler;

                AfterNavigation(e.Exception, null);
            };

            _rootFrame.Navigated        += successHandler;
            _rootFrame.NavigationFailed += failureHandler;
        }
Beispiel #19
0
 public FrameSansNavigation()
 {
     Navigated += new NavigatedEventHandler(FrameSansNavigation_Naviguee);
     NavigationUIVisibility = NavigationUIVisibility.Hidden;
 }
 /// <summary>
 ///   Provides a secure method for setting the NavigatedEventHandler property. This dependency property indicates ....
 /// </summary>
 private static void SetNavigatedEventHandler(DependencyObject d, NavigatedEventHandler value)
 {
     d.SetValue(NavigatedEventHandlerPropertyKey, value);
 }
Beispiel #21
0
        public static Task <object> NavigateAsync(this WebBrowser wb, string link, SynchronizationContext SC)
        {
            if (wb == null)
            {
                throw new ArgumentNullException("wb");
            }
            var tcs = new TaskCompletionSource <object>();
            LoadCompletedEventHandler handler1 = delegate { };
            NavigatedEventHandler     handler2 = delegate { };

            handler1 = (s, e) =>
            {
                dynamic activeX = wb.GetType().InvokeMember("ActiveXInstance",
                                                            BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
                                                            null, wb, new object[] { });
                activeX.Silent = true;

                //if (wb.ReadyState != WebBrowserReadyState.Complete) return;
                //if (PageLoaded.Task.IsCompleted) return;
                tcs.SetResult(wb.Document);
                wb.LoadCompleted -= handler1;
                //wb.Navigated -= handler2;
            };

            handler2 = (s, e) =>
            {
                dynamic doc = ((WebBrowser)s).Document;
                var     url = doc.url as string;
                if (url != null && url.StartsWith("res://ieframe.dll"))
                {
                    tcs.SetException(new InvalidOperationException("Page load error"));
                }
                //wb.LoadCompleted -= handler1;
                wb.Navigated -= handler2;
            };

            wb.LoadCompleted += handler1;
            wb.Navigated     += handler2;
            SC.Post(new SendOrPostCallback(o => { wb.Navigate(link); }), link);
            return(tcs.Task);

            //await Application.Current.Dispatcher.BeginInvoke(new Action(() => { wb.Navigate(link); }));
            //wb.Navigate(new Uri(link));

            /*
             * int TimeElapsed = 0;
             *          while (tcs.Task.Status != TaskStatus.RanToCompletion)
             *          {
             *              await Task.Delay(50);
             *              TimeElapsed++;
             *              if (TimeElapsed >= 1000)
             *              {
             *                 tcs.TrySetResult(true);
             *              }
             *          }
             */
            //надо ли?
            //while (tcs.Task.Status != TaskStatus.RanToCompletion)
            //{
            //    await Task.Delay(50);
            //}
            //await tcs.Task;
        }
        /// <summary>
        /// Navigates the user to the specified view.
        /// </summary>
        /// <param name="parameters">The parameters that are to be passed to the view model.</param>
        /// <typeparam name="TView">The type of the view to which the user is to be navigated.</typeparam>
        /// <exception cref="InvalidOperationException">If the view or the view model can not be instantiated, or the window does not support navigation, an <see cref="InvalidOperationException"/> is thrown.</exception>
        /// <returns>Returns <see cref="NavigationResult.Navigated"/> if the user was successfully navigated and <see cref="NavigationResult.Canceled"/> otherwise.</returns>
        public async Task <NavigationResult> NavigateAsync <TView>(object parameters) where TView : Page
        {
            // Raises the on navigated from event of the current view model, if the view model does not allow to be navigated away from, then the navigation is aborted
            NavigationEventArgs eventArguments = null;

            if (this.CurrentViewModel != null)
            {
                eventArguments = new NavigationEventArgs(NavigationReason.Navigation);
                await this.CurrentViewModel.OnNavigateFromAsync(eventArguments);

                if (eventArguments.Cancel)
                {
                    return(NavigationResult.Canceled);
                }
            }

            // Determines the type of the view model, which can be done via attribute or convention
            Type viewModelType = null;
            ViewModelAttribute viewModelAttribute = typeof(TView).GetTypeInfo().GetCustomAttributes <ViewModelAttribute>().FirstOrDefault();

            if (viewModelAttribute != null)
            {
                viewModelType = viewModelAttribute.ViewModelType;
            }
            else
            {
                this.assemblyTypes = this.assemblyTypes ?? typeof(TView).GetTypeInfo().Assembly.GetTypes();
                string viewModelName = this.ViewModelNamingConvention(typeof(TView).Name);
                viewModelType = this.assemblyTypes.FirstOrDefault(type => type.Name == viewModelName);
            }

            // Instantiates the new view model
            IViewModel viewModel = null;

            if (viewModelType != null)
            {
                try
                {
                    // Lets the IOC container instantiate the view model, so that all dependencies can be injected (including the navigation service itself, which is set as an explitic constructor argument)
                    viewModel = this.iocContainer.GetInstance(viewModelType, this).Inject(parameters) as IViewModel;
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException("The view model could not be instantiated.", e);
                }

                // Checks whether the view model implements the IViewModel interface
                if (viewModel == null)
                {
                    throw new InvalidOperationException("The type of the view model must be an implementation of IViewModel.");
                }
            }

            // Calls the activate event and then the navigate event of the view model
            if (viewModel != null)
            {
                // Raises the activate event of the new view model
                await viewModel.OnActivateAsync();

                // Raises the on navigate to event of the new view model, and checks if it allows to be navigated to
                eventArguments = new NavigationEventArgs(NavigationReason.Navigation);
                await viewModel.OnNavigateToAsync(eventArguments);

                if (eventArguments.Cancel)
                {
                    // Since the view model does not allow to be navigated to, the new view model is deactivated, disposed of, and the navigation is aborted
                    await viewModel.OnDeactivateAsync();

                    viewModel.Dispose();
                    return(NavigationResult.Canceled);
                }
            }

            // Adds the old view to the navigation stack
            if (this.CurrentViewModel != null)
            {
                this.CurrentViewModel.IsInView = false;
            }
            if (this.CurrentView != null)
            {
                this.navigationStack.Push(this.CurrentViewModel);
            }

            // Instantiates the new view
            TaskCompletionSource <Page> taskCompletionSource  = new TaskCompletionSource <Page>();
            NavigatedEventHandler       navigatedEventHandler = (sender, e) => taskCompletionSource.SetResult(e.Content as Page);

            this.navigationFrame.Navigated += navigatedEventHandler;
            this.navigationFrame.Navigate(typeof(TView));
            this.CurrentView = await taskCompletionSource.Task;
            this.navigationFrame.Navigated -= navigatedEventHandler;

            // Sets the view model as data context of the view and sets the new current view model
            this.CurrentView.DataContext = viewModel;
            this.CurrentViewModel        = viewModel;

            // Sets an indicator in the new view model, that it is now in view
            if (this.CurrentViewModel != null)
            {
                this.CurrentViewModel.IsInView = true;
            }

            // Since the navigation was successful, Navigated is returned as a result of the navigation
            return(NavigationResult.Navigated);
        }
        private void NavigateBase(Type viewModelType, Type view, object parameter)
        {
            if (view == null)
            {
                throw new Exception("View not found!");
            }

            ViewModelBase viewModel = null;

            bool useDataContext = NavigationManager.GetViewModelInfo(viewModelType).UseDataContextInsteadOfCreating; //(bool)view.GetTypeInfo().GetCustomAttribute<NavigationViewModelAttribute>()?.UseDataContextInsteadOfCreating;

            if (!useDataContext)
            {
                bool viewModelCachingEnabled = Crystal3.CrystalApplication.GetCurrentAsCrystalApplication().Options.EnableViewModelCaching;
                if (viewModelCachingEnabled)
                {
                    viewModel = Crystal3.CrystalApplication.GetCurrentAsCrystalApplication().ResolveCachedViewModel(viewModelType);
                }
            }

            NavigatingCancelEventHandler navigatingHandler = null;

            navigatingHandler = new NavigatingCancelEventHandler((object sender, Windows.UI.Xaml.Navigation.NavigatingCancelEventArgs e) =>
            {
                NavigationFrame.Navigating -= navigatingHandler;

                if (!useDataContext) //we can't access the data context in this event so don't even bother
                {
                    if (e.NavigationMode == NavigationMode.New || e.NavigationMode == NavigationMode.Refresh)
                    {
                        if (viewModel == null)
                        {
                            viewModel = CreateViewModelFromType(viewModelType) as ViewModelBase;
                        }

                        viewModel.NavigationService = this;

                        if (lastViewModel != null)
                        {
                            e.Cancel = lastViewModel.OnNavigatingFrom(sender, new CrystalNavigationEventArgs(e)
                            {
                                Direction = ConvertToCrystalNavDirections(e.NavigationMode)
                            });
                        }

                        viewModel.OnNavigatingTo(sender, new CrystalNavigationEventArgs(e)
                        {
                            Direction = ConvertToCrystalNavDirections(e.NavigationMode)
                        });
                    }
                    //else if (e.NavigationMode == NavigationMode.Back)
                    //{
                    //    e.Cancel = viewModel.OnNavigatingFrom(sender, e);
                    //}
                }
            });

            NavigatedEventHandler navigatedHandler = null;

            navigatedHandler = new NavigatedEventHandler((object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e) =>
            {
                NavigationFrame.Navigated -= navigatedHandler;

                InvokePreNavigatedEvent(new NavigationServicePreNavigatedSignaledEventArgs(viewModel, new CrystalNavigationEventArgs(e)));

                if (e.NavigationMode == NavigationMode.New)
                {
                    if (lastViewModel != null)
                    {
                        lastViewModel.OnNavigatedFrom(sender, new CrystalNavigationEventArgs(e)
                        {
                            Direction = ConvertToCrystalNavDirections(e.NavigationMode)
                        });

                        viewModelBackStack.Push(lastViewModel);
                    }

                    Page page = e.Content as Page;

                    //page.NavigationCacheMode = NavigationCacheMode.Enabled;

                    if (!useDataContext)
                    {
                        page.DataContext = viewModel;
                    }
                    else
                    {
                        viewModel = page.DataContext as ViewModelBase;
                    }

                    if (viewModel == null)
                    {
                        throw new Exception();
                    }

                    if (viewModel is UIViewModelBase)
                    {
                        ((UIViewModelBase)viewModel).UI.SetUIElement(page);
                    }

                    //page.SetValue(FrameworkElement.DataContextProperty, viewModel);

                    viewModel.OnNavigatedTo(sender, new CrystalNavigationEventArgs(e)
                    {
                        Direction = ConvertToCrystalNavDirections(e.NavigationMode)
                    });

                    lastViewModel = viewModel;
                }
                //else if (e.NavigationMode == NavigationMode.Back)
                //{
                //    viewModel.OnNavigatedFrom(sender, e);
                //}

                InvokeNavigatedEvent(new CrystalNavigationEventArgs(e)
                {
                    Direction = ConvertToCrystalNavDirections(e.NavigationMode), Parameter = e.Parameter
                });

                navigationLock.Set();
            });

            navigationLock.Reset();

            NavigationFrame.Navigated  += navigatedHandler;
            NavigationFrame.Navigating += navigatingHandler;

            NavigationFrame.Navigate(view, parameter);
        }