public override void SaveState(IDataContext state)
 {
     if (_viewModels.Count == 0)
         return;
     var states = new List<IDataContext>();
     foreach (var viewModel in _viewModels)
         states.Insert(0, ViewModelProvider.PreserveViewModel(viewModel, null));
     state.AddOrUpdate(ViewModelsState, new StateList { State = states });
 }
Пример #2
0
 public static IAsyncOperation <TResult> ShowAsync <TResult>([NotNull] this IHasResultViewModel <TResult> viewModel, IDataContext context = null)
 {
     Should.NotBeNull(viewModel, nameof(viewModel));
     context = context.ToNonReadOnly();
     context.AddOrUpdate(NavigationConstants.ViewModel, viewModel);
     return(viewModel
            .GetIocContainer(true)
            .Get <IViewModelPresenter>()
            .ShowAsync(context)
            .ContinueWith <IHasResultViewModel <TResult>, TResult>((vm, result) => vm.Result));
 }
Пример #3
0
        protected virtual void NavigateInternal(IViewModel viewModel, IDataContext context, TaskCompletionSource <bool> tcs)
        {
            if (ReferenceEquals(viewModel, CurrentViewModel))
            {
                tcs.SetResult(true);
                return;
            }
            //The view model is already shown as page and we need to bring it to front
            if (viewModel.Settings.State.Contains(IsNavigatedConstant))
            {
                context.AddOrUpdate(BringToFront, true);
            }

            context.AddOrUpdate(NavigatedTaskConstant, tcs);
            string viewName    = viewModel.GetViewName(context);
            var    mappingItem = ViewMappingProvider.FindMappingForViewModel(viewModel.GetType(), viewName, true);
            var    parameter   = GenerateNavigationParameter(viewModel);

            NavigationService.Navigate(mappingItem, parameter, context);
        }
Пример #4
0
 private void ClearNavigationStackIfNeed(IDataContext context)
 {
     if (context == null)
     {
         context = DataContext.Empty;
     }
     if (!context.GetData(NavigationConstants.ClearBackStack) || _frame.BackStack.IsReadOnly)
     {
         return;
     }
     _frame.BackStack.Clear();
     context.AddOrUpdate(NavigationProviderConstants.InvalidateAllCache, true);
 }
Пример #5
0
        protected virtual IDataContext PreserveViewModelInternal(IViewModel viewModel, IDataContext dataContext)
        {
            IDataContext state = viewModel.Settings.State;

            state.AddOrUpdate(ViewModelTypeNameConstant, viewModel.GetType().AssemblyQualifiedName);
            var hasState = viewModel as IHasState;

            if (hasState != null)
            {
                hasState.SaveState(state);
            }
            return(state);
        }
Пример #6
0
        public IDataContext PreserveViewModel(IViewModel viewModel, IDataContext dataContext)
        {
            Should.NotBeNull(viewModel, nameof(viewModel));
            if (dataContext == null)
            {
                dataContext = DataContext.Empty;
            }

            var preserving = Preserving;

            if (preserving != null)
            {
                var args = new ViewModelPreservingEventArgs(viewModel)
                {
                    Context = dataContext
                };
                preserving(this, args);
                dataContext = args.Context ?? DataContext.Empty;
            }
            if (dataContext != DataContext.Empty)
            {
                dataContext = new DataContext(dataContext);
            }
            IDataContext state = PreserveViewModelInternal(viewModel, dataContext);

            GetOrAddViewModelId(viewModel);
            MergeParameters(viewModel.Settings.Metadata, viewModel.Settings.State);
            //Saving parent view model id.
            var parentViewModel = viewModel.GetParentViewModel();

            if (parentViewModel != null)
            {
                var idParent = GetOrAddViewModelId(parentViewModel);
                state.AddOrUpdate(ViewModelConstants.IdParent, idParent);
            }

            OnViewModelPreserved(viewModel, state, dataContext);

            var preserved = Preserved;

            if (preserved != null)
            {
                var args = new ViewModelPreservedEventArgs(viewModel)
                {
                    Context = dataContext, State = state
                };
                preserved.Invoke(this, args);
                return(args.State);
            }
            return(state);
        }
Пример #7
0
        protected virtual void RestoreViewModel([NotNull] Type viewModelType, [NotNull] IDataContext viewModelState, [NotNull] FrameworkElement element,
                                                [NotNull] IDictionary <string, object> state, [NotNull] object args, [NotNull] IDataContext context)
        {
            context = context.ToNonReadOnly();
            context.AddOrUpdate(InitializationConstants.ViewModelType, viewModelType);

#if WINDOWSCOMMON
            context.Add(DynamicViewModelWindowPresenter.RestoredViewConstant, element);
            context.Add(DynamicViewModelWindowPresenter.IsOpenViewConstant, true);
#endif
            IViewModel viewModel = _viewModelProvider.RestoreViewModel(viewModelState, context, false);
            _viewManager.InitializeViewAsync(viewModel, element, context).WithTaskExceptionHandler(this);
            _viewModelPresenter.Restore(viewModel, context);
        }
Пример #8
0
        private static void MergeParameters(IDataContext ctxFrom, IDataContext ctxTo)
        {
            string viewName = ctxFrom.GetData(InitializationConstants.ViewName);

            if (!string.IsNullOrEmpty(viewName))
            {
                ctxTo.AddOrUpdate(InitializationConstants.ViewName, viewName);
            }

            ObservationMode observationMode;

            if (ctxFrom.TryGetData(InitializationConstants.ObservationMode, out observationMode))
            {
                ctxTo.AddOrUpdate(InitializationConstants.ObservationMode, observationMode);
            }

            string bindingName = ctxFrom.GetData(InitializationConstants.ViewModelBindingName);

            if (!string.IsNullOrEmpty(bindingName))
            {
                ctxTo.AddOrUpdate(InitializationConstants.ViewModelBindingName, bindingName);
            }
        }
Пример #9
0
 private bool ClearNavigationStackIfNeed(UIViewController newItem, IDataContext context, bool animated)
 {
     if (context == null)
     {
         context = DataContext.Empty;
     }
     if (context.GetData(NavigationConstants.ClearBackStack) && NavigationController != null)
     {
         NavigationController.SetViewControllers(new[] { newItem }, animated);
         context.AddOrUpdate(NavigationProviderConstants.InvalidateAllCache, true);
         return(true);
     }
     return(false);
 }
Пример #10
0
 /// <summary>
 ///     Initializes the specified <see cref="IViewModel" />.
 /// </summary>
 protected virtual void InitializeViewModel([NotNull] IViewModel viewModel, [NotNull] IDataContext dataContext,
                                            [CanBeNull] IIocContainer iocContainer)
 {
     dataContext = dataContext.ToNonReadOnly();
     if (iocContainer == null)
     {
         iocContainer = CreateViewModelIocContainer(dataContext);
     }
     dataContext.AddOrUpdate(InitializationConstants.IocContainer, iocContainer);
     OnViewModelInitializing(viewModel, dataContext);
     InitializeParentViewModel(viewModel, dataContext.GetData(InitializationConstants.ParentViewModel), dataContext);
     viewModel.InitializeViewModel(dataContext);
     InitializeDisplayName(viewModel);
     MergeParameters(dataContext, viewModel.Settings.Metadata);
 }
        /// <summary>
        ///     Shows the specified <see cref="IViewModel" />.
        /// </summary>
        /// <param name="viewModel">The specified <see cref="IViewModel" /> to show.</param>
        /// <param name="completeCallback">The specified callback.</param>
        /// <param name="viewName">The name of view.</param>
        /// <param name="context">The specified context.</param>
        /// <returns>The operation result task, this task returns the result of the operation.</returns>
        public static IAsyncOperation <bool> ShowAsync <T>([NotNull] this T viewModel,
                                                           Action <T, IOperationResult <bool> > completeCallback, string viewName = null, IDataContext context = null)
            where T : IViewModel
        {
            Should.NotBeNull(viewModel, "viewModel");
            if (viewName != null)
            {
                context = context.ToNonReadOnly();
                context.AddOrUpdate(NavigationConstants.ViewName, viewName);
            }
            IAsyncOperation <bool> operation = viewModel.ShowAsync(context);

            operation.ContinueWith(completeCallback);
            return(operation);
        }
Пример #12
0
        /// <summary>
        ///     Preserves the view models state.
        /// </summary>
        public void PreserveViewModels(IDataContext context)
        {
            if (ItemsSource.Count == 0)
            {
                return;
            }
            var states = new StateList {
                State = new List <IDataContext>()
            };

            for (int index = 0; index < ItemsSource.Count; index++)
            {
                var viewModel = ItemsSource[index];
                states.State.Add(ViewModelProvider.PreserveViewModel(viewModel, DataContext.Empty));
                if (ReferenceEquals(viewModel, SelectedItem))
                {
                    context.AddOrUpdate(SelectedIndex, index);
                }
            }
            if (states.State.Count != 0)
            {
                context.AddOrUpdate(ViewModelState, states);
            }
        }
Пример #13
0
 private void ClearNavigationStackIfNeed(IDataContext context)
 {
     if (context == null)
     {
         context = DataContext.Empty;
     }
     if (!context.GetData(NavigationConstants.ClearBackStack))
     {
         return;
     }
     while (_window.BackStack.OfType <object>().Any())
     {
         _window.RemoveBackEntry();
     }
     context.AddOrUpdate(NavigationProviderConstants.InvalidateAllCache, true);
 }
        public override void SaveState(IDataContext state)
        {
            if (_viewModels.Count == 0)
            {
                return;
            }
            var states = new List <IDataContext>();

            foreach (var viewModel in _viewModels)
            {
                states.Insert(0, ViewModelProvider.PreserveViewModel(viewModel, null));
            }
            state.AddOrUpdate(ViewModelsState, new StateList {
                State = states
            });
        }
Пример #15
0
        /// <summary>
        ///     Tries to show the specified <see cref="IViewModel" />.
        /// </summary>
        /// <param name="viewModel">The specified <see cref="IViewModel" /> to show.</param>
        /// <param name="context">The specified context.</param>
        /// <param name="parentPresenter">The parent presenter, if any.</param>
        public IAsyncOperation <bool?> TryShowAsync(IViewModel viewModel, IDataContext context,
                                                    IViewModelPresenter parentPresenter)
        {
            if (!CanShowViewModel(viewModel, context, parentPresenter))
            {
                return(null);
            }
            var operation = new AsyncOperation <bool?>();

            context = context.ToNonReadOnly();
            context.AddOrUpdate(NavigationConstants.ViewModel, viewModel);
            viewModel.GetIocContainer(true)
            .Get <INavigationProvider>()
            .Navigate(operation.ToOperationCallback(), context);
            return(operation);
        }
        protected virtual void RestoreViewModel([NotNull] Type viewModelType, [NotNull] IDataContext viewModelState, [NotNull] NSObject item, [NotNull] NSCoder coder,
                                                [NotNull] IDataContext context)
        {
            context = context.ToNonReadOnly();
            context.AddOrUpdate(InitializationConstants.ViewModelType, viewModelType);

            if (item is IModalView)
            {
                context.Add(DynamicViewModelWindowPresenter.RestoredViewConstant, item);
                context.Add(DynamicViewModelWindowPresenter.IsOpenViewConstant, true);
            }
            var viewModel = _viewModelProvider.RestoreViewModel(viewModelState, context, false);

            _viewManager.InitializeViewAsync(viewModel, item, context).WithTaskExceptionHandler(this);
            _viewModelPresenter.Restore(viewModel, context);
        }
Пример #17
0
        protected virtual object WrapInternal(object item, WrapperRegistration wrapperRegistration, IDataContext dataContext)
        {
            if (wrapperRegistration.WrapperFactory != null)
            {
                return(wrapperRegistration.WrapperFactory(item, dataContext));
            }
            var wrapperType = wrapperRegistration.Type;

#if PCL_WINRT
            if (wrapperType.GetTypeInfo().IsGenericTypeDefinition)
#else
            if (wrapperType.IsGenericTypeDefinition)
#endif
            { wrapperType = wrapperType.MakeGenericType(item.GetType()); }

            var viewModel = item as IViewModel;
            if (viewModel != null && typeof(IWrapperViewModel).IsAssignableFrom(wrapperType))
            {
                dataContext = dataContext.ToNonReadOnly();
                if (!dataContext.Contains(InitializationConstants.ParentViewModel))
                {
                    var parentViewModel = viewModel.GetParentViewModel();
                    if (parentViewModel != null)
                    {
                        dataContext.AddOrUpdate(InitializationConstants.ParentViewModel, parentViewModel);
                    }
                }
                var vm = (IWrapperViewModel)_viewModelProvider.GetViewModel(wrapperType, dataContext);
                vm.Wrap(viewModel, dataContext);
                return(vm);
            }

#if PCL_WINRT
            var constructor = wrapperType.GetTypeInfo()
                              .DeclaredConstructors
                              .FirstOrDefault(info => !info.IsStatic);
#else
            var constructor = wrapperType
                              .GetConstructors(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic)
                              .FirstOrDefault();
#endif
            if (constructor == null)
            {
                return(null);
            }
            return(constructor.InvokeEx(item));
        }
        public Task NavigateAsync(IOperationCallback callback, IDataContext context)
        {
            Should.NotBeNull(context, nameof(context));
            IViewModel viewModel = context.GetData(NavigationConstants.ViewModel);

            if (viewModel == null)
            {
                throw new InvalidOperationException($"The '{GetType()}' provider doesn't support the DataContext without navigation target.");
            }
            context = context.ToNonReadOnly();
            if (ReferenceEquals(viewModel, CurrentViewModel))
            {
                if (callback != null)
                {
                    CallbackManager.Register(OperationType.PageNavigation, viewModel, callback, context);
                }
                return(Empty.Task);
            }
            //The view model is already shown as page and we need to bring it to front
            if (viewModel.Settings.State.Contains(IsNavigatedConstant))
            {
                context.AddOrUpdate(NavigationProviderConstants.BringToFront, true);
            }

            string viewName    = viewModel.GetViewName(context);
            var    vmType      = viewModel.GetType();
            var    mappingItem = ViewMappingProvider.FindMappingForViewModel(vmType, viewName, true);
            var    id          = Guid.NewGuid().ToString("n");
            var    parameter   = GenerateNavigationParameter(vmType, id);

            var tcs = new TaskCompletionSource <object>();

            CurrentNavigationTask.TryExecuteSynchronously(_ =>
                                                          ThreadManager.InvokeOnUiThreadAsync(() =>
            {
                _navigatedTcs       = tcs;
                _navigationTargetVm = viewModel;
                _currentCallback    = callback;
                _lastContext        = context;
                _currentOperationId = id;
                if (_navigationService.Navigate(mappingItem, parameter, context))
                {
                    ClearCacheIfNeed(context, viewModel);
                }
            }));
            return(tcs.Task);
        }
Пример #19
0
            public bool TryHandle(object sender, object message)
            {
                var target = GetReferenceValue();

                if (target == null)
                {
                    UnsubscribeEventHandler();
                    return(false);
                }
                LastContext.AddOrUpdate(BindingConstants.CurrentEventArgs, message);

                var command = target as ICommand;

                if (command != null)
                {
                    if (_path.IsDebuggable)
                    {
                        var parameter = GetCommandParameter(LastContext);
                        DebugInfo($"Binding invokes command '{command}' with parameter: '{parameter}', event args: '{message}'", new[] { command, parameter, message });
                        command.Execute(GetCommandParameter(LastContext));
                    }
                    else
                    {
                        command.Execute(GetCommandParameter(LastContext));
                    }
                    return(true);
                }
                var actionValue = target as BindingActionValue;

                if (actionValue == null || actionValue.MemberSource.Target == null)
                {
                    UnsubscribeEventHandler();
                    return(false);
                }
                if (_path.IsDebuggable)
                {
                    var args = new[] { GetCommandParameter(LastContext), message, LastContext };
                    DebugInfo($"Binding invokes member '{actionValue.Member.Path}' with parameter: '{args[0]}', event args: '{message}'", args);
                    actionValue.TrySetValue(new[] { GetCommandParameter(LastContext), message, LastContext }, out target);
                }
                else
                {
                    actionValue.TrySetValue(new[] { GetCommandParameter(LastContext), message, LastContext }, out target);
                }
                return(true);
            }
Пример #20
0
        public void SaveState(IDataContext state)
        {
            if (!IsEntityInitialized)
            {
                return;
            }
            var viewModelState = new ViewModelState {
                Order = Entity, IsNewRecord = IsNewRecord
            };

            viewModelState.SetLinks(_oldLinks);
            var selectedProducts = GridViewModel.OriginalItemsSource
                                   .Where(wrapper => wrapper.IsSelected)
                                   .Select(wrapper => wrapper.Model.Id)
                                   .ToList();

            viewModelState.SelectedProducts = selectedProducts;
            state.AddOrUpdate(StateConstant, viewModelState);
        }
Пример #21
0
        /// <summary>
        ///     Occurs on load element state.
        /// </summary>
        public virtual void OnLoadState(FrameworkElement element, IDictionary <string, object> state, object args,
                                        IDataContext context = null)
        {
            Should.NotBeNull(element, "element");
            Should.NotBeNull(state, "state");
            object value;

            if (!state.TryGetValue(VmStateKey, out value))
            {
                return;
            }
            state.Remove(VmStateKey);
            var container = (LazySerializableContainer)value;

            if (container == null)
            {
                return;
            }
            object dataContext = element.DataContext;
            Type   vmType      = Type.GetType(container.ViewModelType, false);

            if (vmType == null || (dataContext != null && dataContext.GetType().Equals(vmType)))
            {
                return;
            }
            context = context.ToNonReadOnly();
            context.AddOrUpdate(InitializationConstants.ViewModelType, vmType);

            //The navigation is already handled.
            var eventArgs = args as NavigationEventArgs;

            if (eventArgs != null && eventArgs.GetHandled())
            {
                eventArgs.SetHandled(false);
                PlatformExtensions.SetViewModelState(eventArgs.Content, container.GetContext(_serializer));
            }
            else
            {
                IViewModel viewModel = _viewModelProvider.RestoreViewModel(container.GetContext(_serializer), context, false);
                _viewManager.InitializeViewAsync(viewModel, element).WithTaskExceptionHandler(this);
                _viewModelPresenter.Restore(viewModel, context);
            }
        }
Пример #22
0
        public virtual bool Navigate(IViewMappingItem source, string parameter, IDataContext dataContext)
        {
            Should.NotBeNull(source, "source");
            if (!RaiseNavigating(new NavigatingCancelEventArgs(source, NavigationMode.New, parameter)))
            {
                return(false);
            }
            if (dataContext == null)
            {
                dataContext = DataContext.Empty;
            }
            var activity = PlatformExtensions.CurrentActivity ?? SplashScreenActivityBase.Current;
            var context  = activity ?? Application.Context;

            var intent = new Intent(context, source.ViewType);

            if (activity == null)
            {
                intent.AddFlags(ActivityFlags.NewTask);
            }
            else if (dataContext.GetData(NavigationConstants.ClearBackStack))
            {
                if (PlatformExtensions.IsApiLessThanOrEqualTo10)
                {
                    intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTop);
                    ServiceProvider.EventAggregator.Publish(this, MvvmActivityMediator.FinishActivityMessage.Instance);
                }
                else
                {
                    intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
                }
                dataContext.AddOrUpdate(NavigationProvider.ClearNavigationCache, true);
            }
            if (parameter != null)
            {
                intent.PutExtra(ParameterString, parameter);
            }
            _isNew     = true;
            _parameter = parameter;
            StartActivity(context, intent, dataContext);
            return(true);
        }
Пример #23
0
        /// <summary>
        ///     Starts the current bootstrapper.
        /// </summary>
        public virtual void Start(IDataContext context = null)
        {
            Initialize();
            context = context.ToNonReadOnly();
            context.AddOrUpdate(NavigationConstants.IsDialog, false);
            var viewModelType = GetMainViewModelType();

            CreateMainViewModel(viewModelType, context)
            .ShowAsync((model, result) =>
            {
                model.Dispose();
                if (ShutdownOnMainViewModelClose)
                {
                    Application.Exit();
                }
            }, context: context);
            if (_autoRunApplication)
            {
                Application.Run();
            }
        }
Пример #24
0
        public bool Navigate(IViewMappingItem source, string parameter, IDataContext dataContext)
        {
            Should.NotBeNull(source, nameof(source));
            if (dataContext == null)
            {
                dataContext = DataContext.Empty;
            }
            dataContext.TryGetData(NavigationProviderConstants.BringToFront, out _bringToFront);
            var bringToFront = _bringToFront;
            var result       = Navigate(source.ViewType, parameter, dataContext.GetData(NavigationConstants.ViewModel));

            if (result)
            {
                if (bringToFront)
                {
                    dataContext.AddOrUpdate(NavigationProviderConstants.InvalidateCache, true);
                }
                ClearNavigationStackIfNeed(dataContext);
            }
            return(result);
        }
Пример #25
0
        /// <summary>
        ///     Starts the current bootstrapper.
        /// </summary>
        public virtual void Start(IDataContext context = null)
        {
            context = context.ToNonReadOnly();
            context.AddOrUpdate(NavigationConstants.IsDialog, false);
            Initialize();
            Type             viewModelType = GetMainViewModelType();
            NavigationWindow rootWindow    = null;
            var mappingProvider            = IocContainer.Get <IViewMappingProvider>();
            IViewMappingItem mapping       = mappingProvider.FindMappingForViewModel(viewModelType, context.GetData(NavigationConstants.ViewName), true);

            if (typeof(Page).IsAssignableFrom(mapping.ViewType))
            {
                rootWindow = CreateNavigationWindow();
                var service = CreateNavigationService(rootWindow);
                IocContainer.BindToConstant(service);
            }
            var vm = CreateMainViewModel(viewModelType, context);

            vm.ShowAsync((model, result) =>
            {
                model.Dispose();
                if (ShutdownOnMainViewModelClose)
                {
                    Application app = Application.Current;
                    if (app != null)
                    {
                        Action action = app.Shutdown;
                        app.Dispatcher.BeginInvoke(action);
                    }
                }
            }, context: context);
            if (rootWindow != null)
            {
                IWindowViewMediator mediator = new WindowViewMediator(rootWindow, vm, IocContainer.Get <IThreadManager>(),
                                                                      IocContainer.Get <IViewManager>(), IocContainer.Get <IOperationCallbackManager>());
                mediator.UpdateView(new ViewManagerEx.WindowView(rootWindow), true, context);
                rootWindow.Show();
            }
        }
Пример #26
0
        private void ClearNavigationStackIfNeed(IDataContext context, Page page, Task task)
        {
            var navigation = _rootPage.Navigation;

            if (navigation == null || context == null || !context.GetData(NavigationConstants.ClearBackStack))
            {
                return;
            }
            task.TryExecuteSynchronously(t =>
            {
                var pages = navigation.NavigationStack.ToList();
                for (int i = 0; i < pages.Count; i++)
                {
                    var toRemove = pages[i];
                    if (toRemove != page)
                    {
                        navigation.RemovePage(toRemove);
                    }
                }
            });
            context.AddOrUpdate(NavigationProvider.ClearNavigationCache, true);
        }
Пример #27
0
        /// <summary>
        ///     Preserves the view model state.
        /// </summary>
        public IDataContext PreserveViewModel(IViewModel viewModel, IDataContext dataContext)
        {
            Should.NotBeNull(viewModel, "viewModel");
            if (dataContext == null)
            {
                dataContext = DataContext.Empty;
            }
            IDataContext state = PreserveViewModelInternal(viewModel, dataContext);

            GetOrAddViewModelId(viewModel);
            MergeParameters(viewModel.Settings.Metadata, viewModel.Settings.State);
            //Saving parent view model id.
            var parentViewModel = viewModel.GetParentViewModel();

            if (parentViewModel != null)
            {
                var idParent = GetOrAddViewModelId(parentViewModel);
                state.AddOrUpdate(IdParentViewModelConstant, idParent);
            }

            OnViewModelPreserved(viewModel, state, dataContext);
            return(state);
        }
        private void ClearNavigationStackIfNeed(IDataContext context)
        {
#if WINDOWS_PHONE
            var page = _frame.Content as Page;
            if (page == null || page.NavigationService == null)
            {
                return;
            }
            var navigationService = page.NavigationService;
            if (context == null)
            {
                context = DataContext.Empty;
            }
            if (!context.GetData(NavigationConstants.ClearBackStack))
            {
                return;
            }
            while (navigationService.BackStack.OfType <object>().Any())
            {
                navigationService.RemoveBackEntry();
            }
            context.AddOrUpdate(NavigationProvider.ClearNavigationCache, true);
#endif
        }
Пример #29
0
        public object Wrap(object item, Type wrapperType, IDataContext dataContext)
        {
            Should.NotBeNull(item, "item");
            Should.NotBeNull(wrapperType, "wrapperType");
            if (wrapperType.IsInstanceOfType(item))
            {
                return(item);
            }
            dataContext = dataContext.ToNonReadOnly();
            object wrapper = null;
            List <WrapperRegistration> list;

            if (_registrations.TryGetValue(wrapperType, out list))
            {
                dataContext.AddOrUpdate(ItemToWrapConstant, item);
                var type = item.GetType();
                for (int i = 0; i < list.Count; i++)
                {
                    WrapperRegistration registration = list[i];
                    if (registration.Condition(type, dataContext))
                    {
                        wrapper = WrapInternal(item, registration, dataContext);
                    }
                }
                dataContext.Remove(ItemToWrapConstant);
            }
            if (wrapper == null)
            {
                wrapper = WrapToDefaultWrapper(item, wrapperType, dataContext);
            }
            if (wrapper == null)
            {
                throw ExceptionManager.WrapperTypeNotSupported(wrapperType);
            }
            return(wrapper);
        }
 private bool ClearNavigationStackIfNeed(UIViewController newItem, IDataContext context, bool animated)
 {
     if (context == null)
         context = DataContext.Empty;
     if (context.GetData(NavigationConstants.ClearBackStack) && NavigationController != null)
     {
         NavigationController.SetViewControllers(new[] { newItem }, animated);
         context.AddOrUpdate(NavigationProviderConstants.InvalidateAllCache, true);
         return true;
     }
     return false;
 }
        public virtual bool Navigate(IViewMappingItem source, string parameter, IDataContext dataContext)
        {
            Should.NotBeNull(source, nameof(source));
            if (dataContext == null)
                dataContext = DataContext.Empty;
            bool bringToFront;
            dataContext.TryGetData(NavigationProviderConstants.BringToFront, out bringToFront);
            if (!RaiseNavigating(new NavigatingCancelEventArgs(source, bringToFront ? NavigationMode.Refresh : NavigationMode.New, parameter)))
                return false;

            UIViewController viewController = null;
            IViewModel viewModel = dataContext.GetData(NavigationConstants.ViewModel);
            if (bringToFront && viewModel != null)
            {
                var viewControllers = new List<UIViewController>(NavigationController.ViewControllers);
                for (int i = 0; i < viewControllers.Count; i++)
                {
                    var controller = viewControllers[i];
                    if (controller.DataContext() == viewModel)
                    {
                        viewControllers.RemoveAt(i);
                        viewController = controller;
                        NavigationController.ViewControllers = viewControllers.ToArray();
                        dataContext.AddOrUpdate(NavigationProviderConstants.InvalidateCache, true);
                        break;
                    }
                }
            }

            if (viewController == null)
            {
                if (viewModel == null)
                    viewController = (UIViewController)ServiceProvider.Get<IViewManager>().GetViewAsync(source, dataContext).Result;
                else
                    viewController = (UIViewController)ViewManager.GetOrCreateView(viewModel, null, dataContext);
            }
            viewController.SetNavigationParameter(parameter);
            bool shouldNavigate = true;
            if (_window != null)
            {
                bool navigated;
                InitializeNavigationController(GetNavigationController(_window, viewController, out navigated));
                shouldNavigate = !navigated;
                _window = null;
            }
            if (shouldNavigate)
            {
                bool animated;
                if (dataContext.TryGetData(NavigationConstants.UseAnimations, out animated))
                {
                    if (viewModel != null)
                        viewModel.Settings.State.AddOrUpdate(NavigationConstants.UseAnimations, animated);
                }
                else
                    animated = UseAnimations;
                if (!ClearNavigationStackIfNeed(viewController, dataContext, animated))
                    NavigationController.PushViewController(viewController, animated);
            }
            var view = viewController as IViewControllerView;
            if (view == null || view.Mediator.IsAppeared)
                RaiseNavigated(viewController, bringToFront ? NavigationMode.Refresh : NavigationMode.New, parameter);
            else
            {
                if (bringToFront)
                    view.Mediator.ViewDidAppearHandler += OnViewDidAppearHandlerRefresh;
                else
                    view.Mediator.ViewDidAppearHandler += OnViewDidAppearHandlerNew;
            }
            return true;
        }
Пример #32
0
 public IList<IDataContext> Parse(object target, string bindingExpression, IList<object> sources, IDataContext context)
 {
     Should.NotBeNull(bindingExpression, nameof(bindingExpression));
     if (context == null)
         context = DataContext.Empty;
     KeyValuePair<KeyValuePair<string, int>, Action<IDataContext>[]>[] bindingValues;
     lock (_cache)
     {
         if (!_cache.TryGetValue(bindingExpression, out bindingValues))
         {
             try
             {
                 if (ReferenceEquals(context, DataContext.Empty))
                     context = _defaultContext;
                 context.AddOrUpdate(BindingBuilderConstants.Target, target);
                 _context = context;
                 _expression = Handle(bindingExpression, context);
                 _tokenizer = CreateTokenizer(Expression);
                 _memberVisitor.Context = context;
                 var value = ParseInternal()
                     .Select((pair, i) => new KeyValuePair<KeyValuePair<string, int>, Action<IDataContext>[]>(new KeyValuePair<string, int>(pair.Key, i), pair.Value))
                     .ToList();
                 value.Sort(MemberComparison);
                 bindingValues = value.ToArray();
                 if (!context.Contains(BindingBuilderConstants.NoCache))
                     _cache[bindingExpression] = bindingValues;
             }
             finally
             {
                 if (ReferenceEquals(_defaultContext, context))
                     _defaultContext.Clear();
                 _tokenizer = null;
                 _expression = null;
                 _context = null;
                 _memberVisitor.Context = null;
             }
         }
     }
     var result = new IDataContext[bindingValues.Length];
     if (sources != null && sources.Count > 0)
     {
         for (int i = 0; i < bindingValues.Length; i++)
         {
             var pair = bindingValues[i];
             var dataContext = new DataContext(context);
             dataContext.AddOrUpdate(BindingBuilderConstants.Target, target);
             if (pair.Key.Value < sources.Count)
             {
                 object src = sources[pair.Key.Value];
                 if (src != null)
                     dataContext.Add(BindingBuilderConstants.Source, src);
             }
             var actions = pair.Value;
             for (int j = 0; j < actions.Length; j++)
                 actions[j].Invoke(dataContext);
             result[i] = dataContext;
         }
     }
     else
     {
         for (int i = 0; i < bindingValues.Length; i++)
         {
             var actions = bindingValues[i].Value;
             var dataContext = new DataContext(context);
             dataContext.AddOrUpdate(BindingBuilderConstants.Target, target);
             for (int j = 0; j < actions.Length; j++)
                 actions[j].Invoke(dataContext);
             result[i] = dataContext;
         }
     }
     return result;
 }
        private void ClearNavigationStackIfNeed(IDataContext context)
        {
#if WINDOWS_PHONE
            var page = _frame.Content as Page;
            if (page == null || page.NavigationService == null)
                return;
            var navigationService = page.NavigationService;
            if (context == null)
                context = DataContext.Empty;
            if (!context.GetData(NavigationConstants.ClearBackStack))
                return;
            while (navigationService.BackStack.OfType<object>().Any())
                navigationService.RemoveBackEntry();
            context.AddOrUpdate(NavigationProvider.ClearNavigationCache, true);
#endif
        }
        private static void MergeParameters(IDataContext ctxFrom, IDataContext ctxTo)
        {
            string viewName = ctxFrom.GetData(InitializationConstants.ViewName);
            if (!string.IsNullOrEmpty(viewName))
                ctxTo.AddOrUpdate(InitializationConstants.ViewName, viewName);

            IocContainerCreationMode creationMode;
            if (ctxFrom.TryGetData(InitializationConstants.IocContainerCreationMode, out creationMode))
                ctxTo.AddOrUpdate(InitializationConstants.IocContainerCreationMode, creationMode);

            ObservationMode observationMode;
            if (ctxFrom.TryGetData(InitializationConstants.ObservationMode, out observationMode))
                ctxTo.AddOrUpdate(InitializationConstants.ObservationMode, observationMode);
        }
        public Task NavigateAsync(IOperationCallback callback, IDataContext context)
        {
            Should.NotBeNull(context, nameof(context));
            IViewModel viewModel = context.GetData(NavigationConstants.ViewModel);
            if (viewModel == null)
                throw new InvalidOperationException($"The '{GetType()}' provider doesn't support the DataContext without navigation target.");
            context = context.ToNonReadOnly();
            if (ReferenceEquals(viewModel, CurrentViewModel))
            {
                if (callback != null)
                    CallbackManager.Register(OperationType.PageNavigation, viewModel, callback, context);
                return Empty.Task;
            }
            //The view model is already shown as page and we need to bring it to front
            if (viewModel.Settings.State.Contains(IsNavigatedConstant))
                context.AddOrUpdate(NavigationProviderConstants.BringToFront, true);

            string viewName = viewModel.GetViewName(context);
            var vmType = viewModel.GetType();
            var mappingItem = ViewMappingProvider.FindMappingForViewModel(vmType, viewName, true);
            var id = Guid.NewGuid().ToString("n");
            var parameter = GenerateNavigationParameter(vmType, id);

            var tcs = new TaskCompletionSource<object>();
            CurrentNavigationTask.TryExecuteSynchronously(_ =>
                ThreadManager.InvokeOnUiThreadAsync(() =>
                {
                    _navigatedTcs = tcs;
                    _navigationTargetVm = viewModel;
                    _currentCallback = callback;
                    _lastContext = context;
                    _currentOperationId = id;
                    if (_navigationService.Navigate(mappingItem, parameter, context))
                        ClearCacheIfNeed(context, viewModel);
                }));
            return tcs.Task;
        }
 public virtual void SaveState(IDataContext state)
 {
     var selectedItem = SelectedItem;
     if (selectedItem != null)
         state.AddOrUpdate(StateKey, ViewModelProvider.PreserveViewModel(selectedItem, null));
 }
        private void ClearNavigationStackIfNeed(IDataContext context)
        {
#if WINDOWSCOMMON
            if (context == null)
                context = DataContext.Empty;
            if (!context.GetData(NavigationConstants.ClearBackStack) || _frame.BackStack.IsReadOnly)
                return;
            _frame.BackStack.Clear();
            context.AddOrUpdate(NavigationProvider.ClearNavigationCache, true);
#endif
        }
 public void SaveState(IDataContext state)
 {
     state.AddOrUpdate("Depth", Depth);
 }
        public virtual bool Navigate(IViewMappingItem source, string parameter, IDataContext dataContext)
        {
            Should.NotBeNull(source, nameof(source));
            if (dataContext == null)
                dataContext = DataContext.Empty;
            bool bringToFront;
            dataContext.TryGetData(NavigationProviderConstants.BringToFront, out bringToFront);
            if (!RaiseNavigating(new NavigatingCancelEventArgs(source, bringToFront ? NavigationMode.Refresh : NavigationMode.New, parameter)))
                return false;
            var activity = PlatformExtensions.CurrentActivity ?? SplashScreenActivityBase.Current;
            var context = activity ?? Application.Context;

            var intent = new Intent(context, source.ViewType);
            if (activity == null)
                intent.AddFlags(ActivityFlags.NewTask);
            else if (dataContext.GetData(NavigationConstants.ClearBackStack))
            {
                if (PlatformExtensions.IsApiLessThanOrEqualTo10)
                    intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTop);
                else
                    intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
                ServiceProvider.EventAggregator.Publish(this, MvvmActivityMediator.FinishActivityMessage.Instance);
                dataContext.AddOrUpdate(NavigationProviderConstants.InvalidateAllCache, true);
            }
            if (parameter != null)
                intent.PutExtra(ParameterString, parameter);

            if (bringToFront)
            {
                _isReorder = true;
                //http://stackoverflow.com/questions/20695522/puzzling-behavior-with-reorder-to-front
                //http://code.google.com/p/android/issues/detail?id=63570#c2
                bool closed = false;
                if (PlatformExtensions.IsApiGreaterThanOrEqualTo19)
                {
                    var viewModel = dataContext.GetData(NavigationConstants.ViewModel);
                    if (viewModel != null)
                    {
                        var view = viewModel.Settings.Metadata.GetData(ViewModelConstants.View);
                        var activityView = ToolkitExtensions.GetUnderlyingView<object>(view) as Activity;
                        if (activityView != null && activityView.IsTaskRoot)
                        {
                            var message = new MvvmActivityMediator.FinishActivityMessage(viewModel);
                            ServiceProvider.EventAggregator.Publish(this, message);
                            closed = message.Finished;
                        }
                    }
                }
                if (!closed)
                    intent.AddFlags(ActivityFlags.ReorderToFront);
                dataContext.AddOrUpdate(NavigationProviderConstants.InvalidateCache, true);
            }
            _isNew = true;
            _parameter = parameter;
            StartActivity(context, intent, source, dataContext);
            return true;
        }
 public void SaveState(IDataContext state)
 {
     state.AddOrUpdate("Name", DisplayName);
     state.AddOrUpdate("Id", Id);
 }
        /// <summary>
        ///     Restores the view model from state context.
        /// </summary>
        /// <param name="viewModelState">The specified state <see cref="IDataContext" />.</param>
        /// <param name="throwOnError">
        ///     <c>true</c> to throw an exception if the view model cannot be restored; <c>false</c> to return null.
        /// </param>
        /// <param name="dataContext">The specified <see cref="IDataContext" />.</param>
        /// <returns>
        ///     An instance of <see cref="IViewModel" />.
        /// </returns>
        public IViewModel RestoreViewModel(IDataContext viewModelState, IDataContext dataContext, bool throwOnError)
        {
            try
            {
                dataContext = dataContext.ToNonReadOnly();
                if (viewModelState == null)
                    viewModelState = DataContext.Empty;
                else
                    dataContext.Merge(viewModelState);

                IViewModel viewModel;
                if (!dataContext.GetData(InitializationConstants.IgnoreRestoredViewModelCache))
                {
                    Guid id;
                    if (viewModelState.TryGetData(IdViewModelConstant, out id))
                    {
                        viewModel = GetOrAddRestoredViewModel(id).GetViewModel();
                        if (viewModel != null)
                            return viewModel;
                    }
                }

                RestoredViewModel restoredParentViewModel = null;
                IViewModel parentViewModel = null;
                Guid idParent;
                if (viewModelState.TryGetData(IdParentViewModelConstant, out idParent))
                {
                    restoredParentViewModel = GetOrAddRestoredViewModel(idParent);
                    parentViewModel = restoredParentViewModel.GetViewModel();
                    if (parentViewModel != null)
                        dataContext.AddOrUpdate(InitializationConstants.ParentViewModel, parentViewModel);
                }

                viewModel = RestoreViewModel(viewModelState, dataContext);
                if (viewModel != null)
                {
                    if (restoredParentViewModel != null && parentViewModel == null)
                        restoredParentViewModel.AddChildViewModel(viewModel);
                    OnViewModelRestored(viewModel, viewModelState, dataContext);
                    Tracer.TraceViewModel(AuditAction.Restored, viewModel);
                    if (ReferenceEquals(viewModelState, DataContext.Empty))
                        Tracer.Warn("The view model '{0}' was restored without state.", viewModel);
                    return viewModel;
                }

                if (throwOnError)
                    throw ExceptionManager.ViewModelCannotBeRestored();
            }
            catch (Exception e)
            {
                if (throwOnError)
                    throw;
                Tracer.Warn(e.Flatten(true));
            }
            return null;
        }
Пример #42
0
        public IViewModel RestoreViewModel(IDataContext viewModelState, IDataContext dataContext, bool throwOnError)
        {
            try
            {
                dataContext = dataContext.ToNonReadOnly();
                if (viewModelState == null)
                {
                    viewModelState = DataContext.Empty;
                }
                else
                {
                    dataContext.Merge(viewModelState);
                }

                IViewModel viewModel;
                if (!dataContext.GetData(InitializationConstants.IgnoreViewModelCache))
                {
                    Guid id;
                    if (viewModelState.TryGetData(IdViewModelConstant, out id))
                    {
                        viewModel = GetOrAddRestoredViewModel(id).GetViewModel();
                        if (viewModel != null)
                        {
                            return(viewModel);
                        }
                    }
                }

                RestoredViewModel restoredParentViewModel = null;
                IViewModel        parentViewModel         = null;
                Guid idParent;
                if (viewModelState.TryGetData(IdParentViewModelConstant, out idParent))
                {
                    restoredParentViewModel = GetOrAddRestoredViewModel(idParent);
                    parentViewModel         = restoredParentViewModel.GetViewModel();
                    if (parentViewModel != null)
                    {
                        dataContext.AddOrUpdate(InitializationConstants.ParentViewModel, parentViewModel);
                    }
                }

                var restoring = Restoring;
                if (restoring != null)
                {
                    var args = new ViewModelRestoringEventArgs {
                        Context = dataContext, ViewModelState = viewModelState
                    };
                    restoring(this, args);
                    dataContext = args.Context ?? DataContext.Empty;
                }

                viewModel = RestoreViewModelInternal(viewModelState, dataContext);
                if (viewModel != null)
                {
                    if (restoredParentViewModel != null && parentViewModel == null)
                    {
                        restoredParentViewModel.AddChildViewModel(viewModel);
                    }
                    OnViewModelRestored(viewModel, viewModelState, dataContext);

                    var restored = Restored;
                    if (restored != null)
                    {
                        var args = new ViewModelRestoredEventArgs(viewModel)
                        {
                            Context        = dataContext,
                            ViewModelState = viewModelState
                        };
                        restored(this, args);
                    }
                    Tracer.TraceViewModel(AuditAction.Restored, viewModel);
                    if (ReferenceEquals(viewModelState, DataContext.Empty))
                    {
                        Tracer.Warn("The view model '{0}' was restored without state.", viewModel);
                    }
                    return(viewModel);
                }

                if (throwOnError)
                {
                    throw ExceptionManager.ViewModelCannotBeRestored();
                }
            }
            catch (Exception e)
            {
                if (throwOnError)
                {
                    throw;
                }
                Tracer.Warn(e.Flatten(true));
            }
            return(null);
        }
 protected virtual ISingleBindingSourceAccessor GetAccessor(object model, string path, IDataContext context, bool isSource, Func<IDataContext, object> commandParameterDelegate = null)
 {
     var source = new MultiPathObserver(model, BindingPath.Create(path), false);
     if (commandParameterDelegate != null)
     {
         context = context.ToNonReadOnly();
         context.AddOrUpdate(BindingBuilderConstants.CommandParameter, commandParameterDelegate);
     }
     return new BindingSourceAccessor(source, context, !isSource);
 }
        public virtual bool Navigate(IViewMappingItem source, string parameter, IDataContext dataContext)
        {
            Should.NotBeNull(source, nameof(source));
            if (_rootPage == null)
                return false;
            if (dataContext == null)
                dataContext = DataContext.Empty;
            dataContext.TryGetData(NavigationProviderConstants.BringToFront, out _bringToFront);
            if (!RaiseNavigating(new NavigatingCancelEventArgs(source, _bringToFront ? NavigationMode.Refresh : NavigationMode.New, parameter, true, false)))
                return false;

            var viewModel = dataContext.GetData(NavigationConstants.ViewModel);
            bool animated;
            if (dataContext.TryGetData(NavigationConstants.UseAnimations, out animated))
            {
                if (viewModel != null)
                    viewModel.Settings.State.AddOrUpdate(NavigationConstants.UseAnimations, animated);
            }
            else
                animated = UseAnimations;
            Page page = null;
            if (_bringToFront && viewModel != null)
            {
                var navigation = _rootPage.Navigation;
                if (navigation != null)
                {
                    for (int i = 0; i < navigation.NavigationStack.Count; i++)
                    {
                        var p = navigation.NavigationStack[i];
                        if (p.BindingContext == viewModel)
                        {
                            page = p;
                            navigation.RemovePage(p);
                            dataContext.AddOrUpdate(NavigationProviderConstants.InvalidateCache, true);
                            break;
                        }
                    }
                }
            }
            if (page == null)
            {
                if (viewModel == null)
                    page = (Page)ServiceProvider.Get<IViewManager>().GetViewAsync(source, dataContext).Result;
                else
                    page = (Page)ViewManager.GetOrCreateView(viewModel, null, dataContext);
            }
            page.SetNavigationParameter(parameter);
            ClearNavigationStackIfNeed(dataContext, page, _rootPage.PushAsync(page, animated));
            return true;
        }
Пример #45
0
 private void ClearNavigationStackIfNeed(IDataContext context, Page page, Task task)
 {
     var navigation = _rootPage.Navigation;
     if (navigation == null || context == null || !context.GetData(NavigationConstants.ClearBackStack))
         return;
     task.TryExecuteSynchronously(t =>
     {
         var pages = navigation.NavigationStack.ToList();
         for (int i = 0; i < pages.Count; i++)
         {
             var toRemove = pages[i];
             if (toRemove != page)
                 navigation.RemovePage(toRemove);
         }
     });
     context.AddOrUpdate(NavigationProvider.ClearNavigationCache, true);
 }
        public virtual bool Navigate(IViewMappingItem source, string parameter, IDataContext dataContext)
        {
            Should.NotBeNull(source, "source");
            if (!RaiseNavigating(new NavigatingCancelEventArgs(source, NavigationMode.New, parameter)))
                return false;
            if (dataContext == null)
                dataContext = DataContext.Empty;
            var activity = PlatformExtensions.CurrentActivity ?? SplashScreenActivityBase.Current;
            var context = activity ?? Application.Context;

            var intent = new Intent(context, source.ViewType);
            if (activity == null)
                intent.AddFlags(ActivityFlags.NewTask);
            else if (dataContext.GetData(NavigationConstants.ClearBackStack))
            {
                if (PlatformExtensions.IsApiLessThanOrEqualTo10)
                {
                    intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTop);
                    ServiceProvider.EventAggregator.Publish(this, MvvmActivityMediator.FinishActivityMessage.Instance);
                }
                else
                    intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
                dataContext.AddOrUpdate(NavigationProvider.ClearNavigationCache, true);
            }
            if (parameter != null)
                intent.PutExtra(ParameterString, parameter);
            _isNew = true;
            _parameter = parameter;
            StartActivity(context, intent, dataContext);
            return true;
        }
        public IViewModel RestoreViewModel(IDataContext viewModelState, IDataContext dataContext, bool throwOnError)
        {
            try
            {
                dataContext = dataContext.ToNonReadOnly();
                if (viewModelState == null)
                    viewModelState = DataContext.Empty;
                else
                    dataContext.Merge(viewModelState);

                IViewModel viewModel;
                if (!dataContext.GetData(InitializationConstants.IgnoreViewModelCache))
                {
                    Guid id;
                    if (viewModelState.TryGetData(ViewModelConstants.Id, out id))
                    {
                        viewModel = GetOrAddCachedViewModel(id).GetViewModel();
                        if (viewModel != null)
                            return viewModel;
                    }
                }

                CachedViewModel restoredParentViewModel = null;
                IViewModel parentViewModel = null;
                Guid idParent;
                if (viewModelState.TryGetData(ViewModelConstants.IdParent, out idParent))
                {
                    restoredParentViewModel = GetOrAddCachedViewModel(idParent);
                    parentViewModel = restoredParentViewModel.GetViewModel();
                    if (parentViewModel != null)
                        dataContext.AddOrUpdate(InitializationConstants.ParentViewModel, parentViewModel);
                }

                var restoring = Restoring;
                if (restoring != null)
                {
                    var args = new ViewModelRestoringEventArgs { Context = dataContext, ViewModelState = viewModelState };
                    restoring(this, args);
                    dataContext = args.Context ?? DataContext.Empty;
                }

                viewModel = RestoreViewModelInternal(viewModelState, dataContext);
                if (viewModel != null)
                {
                    if (restoredParentViewModel != null && parentViewModel == null)
                        restoredParentViewModel.AddChildViewModel(viewModel);
                    OnViewModelRestored(viewModel, viewModelState, dataContext);

                    var restored = Restored;
                    if (restored != null)
                    {
                        var args = new ViewModelRestoredEventArgs(viewModel)
                        {
                            Context = dataContext,
                            ViewModelState = viewModelState
                        };
                        restored(this, args);
                    }
                    Tracer.TraceViewModel(ViewModelLifecycleType.Restored, viewModel);
                    if (ReferenceEquals(viewModelState, DataContext.Empty))
                        Tracer.Warn("The view model '{0}' was restored without state.", viewModel);
                    return viewModel;
                }

                if (throwOnError)
                    throw ExceptionManager.ViewModelCannotBeRestored();
            }
            catch (Exception e)
            {
                if (throwOnError)
                    throw;
                Tracer.Warn(e.Flatten(true));
            }
            return null;
        }
 public INavigationOperation TryShowAsync(IViewModel viewModel, IDataContext context,
     IViewModelPresenter parentPresenter)
 {
     if (!CanShowViewModel(viewModel, context, parentPresenter))
         return null;
     var tcs = new TaskCompletionSource<object>();
     var operation = new NavigationOperation(tcs.Task);
     context = context.ToNonReadOnly();
     context.AddOrUpdate(NavigationConstants.ViewModel, viewModel);
     var provider = viewModel.GetIocContainer(true).Get<INavigationProvider>();
     provider.CurrentNavigationTask.TryExecuteSynchronously(_ =>
     {
         try
         {
             var task = provider.NavigateAsync(operation.ToOperationCallback(), context);
             tcs.TrySetFromTask(task);
         }
         catch (Exception e)
         {
             tcs.TrySetException(e);
             throw;
         }
     });
     return operation;
 }
 public void SaveState(IDataContext state)
 {
     IList<IEntityStateEntry> changes = _trackingCollection.GetChanges();
     if (changes.Count != 0)
         state.AddOrUpdate(StateConstant, new TrackingCollection(changes));
 }
 private void ClearNavigationStackIfNeed(IDataContext context)
 {
     if (context == null)
         context = DataContext.Empty;
     if (!context.GetData(NavigationConstants.ClearBackStack))
         return;
     while (_frame.BackStack.OfType<object>().Any())
         _frame.RemoveBackEntry();
     context.AddOrUpdate(NavigationProvider.ClearNavigationCache, true);
 }
 public bool Navigate(IViewMappingItem source, string parameter, IDataContext dataContext)
 {
     Should.NotBeNull(source, nameof(source));
     if (dataContext == null)
         dataContext = DataContext.Empty;
     dataContext.TryGetData(NavigationProviderConstants.BringToFront, out _bringToFront);
     var bringToFront = _bringToFront;
     var result = Navigate(source.ViewType, parameter, dataContext.GetData(NavigationConstants.ViewModel));
     if (result)
     {
         if (bringToFront)
             dataContext.AddOrUpdate(NavigationProviderConstants.InvalidateCache, true);
         ClearNavigationStackIfNeed(dataContext);
     }
     return result;
 }
 void IHasState.SaveState(IDataContext state)
 {
     state.AddOrUpdate(nameof(Text), Text);
 }
 private void ClearNavigationStackIfNeed(IDataContext context)
 {
     if (context == null)
         context = DataContext.Empty;
     if (!context.GetData(NavigationConstants.ClearBackStack) || _frame.BackStack.IsReadOnly)
         return;
     _frame.BackStack.Clear();
     context.AddOrUpdate(NavigationProviderConstants.InvalidateAllCache, true);
 }