protected virtual IViewModel GetViewModelForView([NotNull] NavigationEventArgsBase args, [CanBeNull] IViewModel navigationViewModel, [NotNull] INavigationContext context, [NotNull] Type vmType) { var view = args.Content; if (navigationViewModel != null) { ViewManager.InitializeViewAsync(navigationViewModel, view, context); return(navigationViewModel); } if (HasViewModel(view, vmType)) { return((IViewModel)ToolkitExtensions.GetDataContext(view)); } IDataContext viewModelState = null; #if WINDOWS_UWP viewModelState = UwpToolkitExtensions.GetViewModelState(view); if (viewModelState != null) { UwpToolkitExtensions.SetViewModelState(view, null); } #endif var vm = ViewModelProvider.RestoreViewModel(viewModelState, new DataContext { { InitializationConstants.ViewModelType, vmType } }, true); if (vm != null) { ViewManager.InitializeViewAsync(vm, view, context); if (viewModelState == null && !vm.Settings.Metadata.GetData(NavigationConstants.DoNotDisposeNoStateViewModel)) { vm.RegisterNavigationOperation(OperationType.PageNavigation, context) .ContinueWith <IViewModel>((viewModel, result) => viewModel.Dispose()); } } return(vm); }
public void OnLoadState(FrameworkElement element, IDictionary <string, object> state, object args, IDataContext context = null) { Should.NotBeNull(element, nameof(element)); Should.NotBeNull(state, nameof(state)); object value; if (!state.TryGetValue(VmTypeKey, out value)) { return; } state.Remove(VmTypeKey); object dataContext = element.DataContext; Type vmType = Type.GetType(value as string, false); if (vmType == null || (dataContext != null && dataContext.GetType().Equals(vmType))) { return; } if (context == null) { context = DataContext.Empty; } var viewModelState = RestoreViewModelState(element, state, args, context); //The navigation is already handled. var eventArgs = args as NavigationEventArgs; if (eventArgs != null && eventArgs.GetHandled()) { eventArgs.SetHandled(false); UwpToolkitExtensions.SetViewModelState(eventArgs.Content, viewModelState); } else { RestoreViewModel(vmType, viewModelState, element, state, args, context); } }
protected virtual IViewModel GetViewModelForView([NotNull] NavigationEventArgsBase args, [CanBeNull] IViewModel navigationViewModel, [NotNull] INavigationContext context, [NotNull] Type vmType) { var view = args.Content; if (navigationViewModel != null) { ViewManager.InitializeViewAsync(navigationViewModel, view, context); return(navigationViewModel); } if (HasViewModel(view, vmType)) { return((IViewModel)ToolkitExtensions.GetDataContext(view)); } IDataContext viewModelState = null; #if WINDOWS_UWP viewModelState = UwpToolkitExtensions.GetViewModelState(view); if (viewModelState != null) { UwpToolkitExtensions.SetViewModelState(view, null); } #endif var vm = ViewModelProvider.RestoreViewModel(viewModelState, new DataContext { { InitializationConstants.ViewModelType, vmType } }, true); if (vm != null) { ViewManager.InitializeViewAsync(vm, view, context); } return(vm); }