private static void NotifyActiveViewsNavigatingFrom(INavigationContext navigationContext, object[] activeViews)
 {
     foreach (var item in activeViews)
     {
         MvvmHelpers.OnNavigatedFrom(item, navigationContext);
     }
 }
Exemple #2
0
        protected override void Invoke(object parameter)
        {
            var args = parameter as InteractionRequestedEventArgs;

            if (args == null)
            {
                return;
            }
            var notification = args.Context as PopupNotification;

            var window = new PopupWindow();
            Action <IInteractionRequestAware> setNotificationAndClose = (iira) =>
            {
                iira.Notification      = notification;
                iira.FinishInteraction = () =>
                {
                    args.Callback();
                    window.Close();
                    window = null;
                };
            };

            MvvmHelpers.ViewAndViewModelAction(window.Content, setNotificationAndClose);
            window.Show();
        }
        public IDialogResult ShowWindow(string name)
        {
            IDialogResult dialogResult = new DialogResult(ButtonResult.None);

            var content = _containerExtension.Resolve <object>(name);

            if (!(content is Window dialogContent))
            {
                throw new NullReferenceException("A dialog's content must be a Window");
            }

            if (dialogContent is Window view && view.DataContext is null && ViewModelLocator.GetAutoWireViewModel(view) is null)
            {
                ViewModelLocator.SetAutoWireViewModel(view, true);
            }

            if (!(dialogContent.DataContext is IDialogAware viewModel))
            {
                throw new NullReferenceException("A dialog's ViewModel must implement the IDialogAware interface");
            }

            if (dialogContent is IDialogWindow dialogWindow)
            {
                ConfigureDialogWindowEvents(dialogWindow, result => { dialogResult = result; });
            }

            MvvmHelpers.ViewAndViewModelAction <IDialogAware>(viewModel, d => d.OnDialogOpened(null));
            dialogContent.ShowDialog();

            return(dialogResult);
        }
        private static bool PersistInHistory(object view)
        {
            bool persist = true;

            MvvmHelpers.ViewAndViewModelAction <IJournalAware>(view, ija => { persist &= ija.PersistInHistory(); });
            return(persist);
        }
        private void ExecuteNavigation(NavigationContext navigationContext, object[] activeViews, Action <NavigationResult> navigationCallback)
        {
            try
            {
                NotifyActiveViewsNavigatingFrom(navigationContext, activeViews);

                object view = this.regionNavigationContentLoader.LoadContent(this.Region, navigationContext);

                // Raise the navigating event just before activing the view.
                this.RaiseNavigating(navigationContext);

                this.Region.Activate(view);

                // Update the navigation journal before notifying others of navigaton
                IRegionNavigationJournalEntry journalEntry = this.serviceLocator.GetInstance <IRegionNavigationJournalEntry>();
                journalEntry.Uri        = navigationContext.Uri;
                journalEntry.Parameters = navigationContext.Parameters;
                this.journal.RecordNavigation(journalEntry);

                // The view can be informed of navigation
                Action <INavigationAware> action = (n) => n.OnNavigatedTo(navigationContext);
                MvvmHelpers.ViewAndViewModelAction(view, action);

                navigationCallback(new NavigationResult(navigationContext, true));

                // Raise the navigated event when navigation is completed.
                this.RaiseNavigated(navigationContext);
            }
            catch (Exception e)
            {
                this.NotifyNavigationFailed(navigationContext, navigationCallback, e);
            }
        }
Exemple #6
0
        protected override void PrepareContentForWindow(INotification notification, Window wrapperWindow)
        {
            void setNotificationAndClose(IInteractionRequestAware iira)
            {
                iira.Notification      = notification;
                iira.FinishInteraction = () => wrapperWindow.Close();
            }

            if (this.WindowContent != null)
            {
                // We set the WindowContent as the content of the window.
                if (wrapperWindow is Views.Dialogs.PopupMetroWindow metroWindow)
                {
                    metroWindow.MainControl.Content = this.WindowContent;
                    MvvmHelpers.ViewAndViewModelAction <IInteractionRequestAware>(metroWindow.MainControl.Content, setNotificationAndClose);
                    return;
                }
                else
                {
                    wrapperWindow.Content = this.WindowContent;
                }
            }
            else if (this.WindowContentType != null)
            {
                wrapperWindow.Content = ServiceLocator.Current.GetInstance(this.WindowContentType);
            }
            else
            {
                return;
            }

            MvvmHelpers.ViewAndViewModelAction <IInteractionRequestAware>(wrapperWindow.Content, setNotificationAndClose);
        }
        protected override void OnDetaching()
        {
            RegionManager.SetRegionManager(this.AssociatedObject, null);
            Action <IRegionManagerAware> resetRegionManager = x => x.RegionManager = null;

            MvvmHelpers.ViewAndViewModelAction(this.AssociatedObject, resetRegionManager);
        }
 private static void InvokeOnNavigationAwareElements(IEnumerable <object> items, Action <INavigationAware> invocation)
 {
     foreach (var item in items)
     {
         MvvmHelpers.ViewAndViewModelAction(item, invocation);
     }
 }
Exemple #9
0
        /// <summary>
        /// Runs the initialization sequence to configure the Prism application.
        /// </summary>
        protected virtual void Initialize()
        {
            ContainerLocator.SetContainerExtension(CreateContainerExtension);
            _containerExtension = ContainerLocator.Current;
            _moduleCatalog      = CreateModuleCatalog();
            RegisterRequiredTypes(_containerExtension);
            RegisterTypes(_containerExtension);
            _containerExtension.FinalizeExtension();

            ConfigureModuleCatalog(_moduleCatalog);

            var regionAdapterMappings = _containerExtension.Resolve <RegionAdapterMappings>();

            ConfigureRegionAdapterMappings(regionAdapterMappings);

            var defaultRegionBehaviors = _containerExtension.Resolve <IRegionBehaviorFactory>();

            ConfigureDefaultRegionBehaviors(defaultRegionBehaviors);

            RegisterFrameworkExceptionTypes();

            var shell = CreateShell();

            if (shell != null)
            {
                MvvmHelpers.AutowireViewModel(shell);
                RegionManager.SetRegionManager(shell, _containerExtension.Resolve <IRegionManager>());
                RegionManager.UpdateRegions();
                InitializeShell(shell);
            }

            InitializeModules();
        }
Exemple #10
0
        /// <summary>
        /// Configure <see cref="IDialogWindow"/> content.
        /// </summary>
        /// <param name="dialogName">The name of the dialog to show.</param>
        /// <param name="window">The hosting window.</param>
        /// <param name="parameters">The parameters to pass to the dialog.</param>
        protected virtual async Task ConfigureDialogWindowContent(string dialogName, IDialogWindow window, IDialogParameters parameters)
        {
            var content = _containerExtension.Resolve <object>(dialogName);

            if (!(content is FrameworkElement dialogContent))
            {
                throw new NullReferenceException("A dialog's content must be a FrameworkElement");
            }

            MvvmHelpers.AutowireViewModel(dialogContent);

            if (!(dialogContent.DataContext is IDialogAware viewModel))
            {
                throw new NullReferenceException("A dialog's ViewModel must implement the IDialogAware interface");
            }

            if (!(dialogContent.DataContext is IDialogAsyncAware asyncviewModel))
            {
                throw new NullReferenceException("A dialog's ViewModel must implement the IDialogAsyncAware interface");
            }

            if (viewModel != null)
            {
                ConfigureDialogWindowProperties(window, dialogContent, viewModel);
                viewModel.OnDialogOpened(parameters);
            }
            else if (asyncviewModel != null)
            {
                ConfigureDialogWindowProperties(window, dialogContent, asyncviewModel);
                await asyncviewModel.OnDialogOpenedAsync(parameters);
            }
        }
Exemple #11
0
        private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach (object item in e.NewItems)
                {
                    Action <IActiveAware> invocation = activeAware => activeAware.IsActive = true;

                    MvvmHelpers.ViewAndViewModelAction(item, invocation);
                    InvokeOnSynchronizedActiveAwareChildren(item, invocation);
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                foreach (object item in e.OldItems)
                {
                    Action <IActiveAware> invocation = activeAware => activeAware.IsActive = false;

                    MvvmHelpers.ViewAndViewModelAction(item, invocation);
                    InvokeOnSynchronizedActiveAwareChildren(item, invocation);
                }
            }

            // May need to handle other action values (reset, replace). Currently the ViewsCollection class does not raise CollectionChanged with these values.
        }
        private void ExecuteNavigation(INavigationContext navigationContext, object[] activeViews, Action <IRegionNavigationResult> navigationCallback)
        {
            try
            {
                NotifyActiveViewsNavigatingFrom(navigationContext, activeViews);

                var view = (VisualElement)_regionNavigationContentLoader.LoadContent(Region, navigationContext);

                // Raise the navigating event just before activating the view.
                RaiseNavigating(navigationContext);

                Region.Activate(view);

                // Update the navigation journal before notifying others of navigation
                IRegionNavigationJournalEntry journalEntry = _container.Resolve <IRegionNavigationJournalEntry>();
                journalEntry.Uri        = navigationContext.Uri;
                journalEntry.Parameters = navigationContext.Parameters;

                bool persistInHistory = PersistInHistory(view);

                Journal.RecordNavigation(journalEntry, persistInHistory);

                // The view can be informed of navigation
                MvvmHelpers.OnNavigatedTo(view, navigationContext);

                navigationCallback(new RegionNavigationResult(navigationContext, true));

                // Raise the navigated event when navigation is completed.
                RaiseNavigated(navigationContext);
            }
            catch (Exception e)
            {
                NotifyNavigationFailed(navigationContext, navigationCallback, e);
            }
        }
Exemple #13
0
        private void InvokeOnSynchronizedActiveAwareChildren(object item, Action <IActiveAware> invocation)
        {
            var dependencyObjectView = item as DependencyObject;

            if (dependencyObjectView != null)
            {
                // We are assuming that any scoped region managers are attached directly to the
                // view.
                var regionManager = RegionManager.GetRegionManager(dependencyObjectView);

                // If the view's RegionManager attached property is different from the region's RegionManager,
                // then the view's region manager is a scoped region manager.
                if (regionManager == null || regionManager == this.Region.RegionManager)
                {
                    return;
                }

                var activeViews = regionManager.Regions.SelectMany(e => e.ActiveViews);

                var syncActiveViews = activeViews.Where(ShouldSyncActiveState);

                foreach (var syncActiveView in syncActiveViews)
                {
                    MvvmHelpers.ViewAndViewModelAction(syncActiveView, invocation);
                }
            }
        }
Exemple #14
0
        private async Task ConfigureContentDialogContent(ContentDialog dialog, IDialogParameters parameters)
        {
            MvvmHelpers.AutowireViewModel(dialog);

            object viewModel = dialog.DataContext;

            Initialize(parameters, viewModel);
            await InitializeAsync(parameters, viewModel);
        }
        protected override void OnAttached()
        {
            var rm = ServiceLocator.Current.GetInstance <IRegionManager>();
            var newRegionManager = rm.CreateRegionManager();

            RegionManager.SetRegionManager(this.AssociatedObject, newRegionManager);
            Action <IRegionManagerAware> setRegionManager = x => x.RegionManager = newRegionManager;

            MvvmHelpers.ViewAndViewModelAction(this.AssociatedObject, setRegionManager);
        }
Exemple #16
0
        private static bool PersistInHistory(object[] activeViews)
        {
            bool persist = true;

            if (activeViews.Length > 0)
            {
                MvvmHelpers.ViewAndViewModelAction <IJournalAware>(activeViews[0], ija => { persist &= ija.PersistInHistory(); });
            }
            return(persist);
        }
Exemple #17
0
 private void Views_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
 {
     if (e.Action == NotifyCollectionChangedAction.Remove)
     {
         foreach (var item in e.OldItems)
         {
             Action <IDestructible> invocation = destructible => destructible.Destroy();
             MvvmHelpers.ViewAndViewModelAction(item, invocation);
         }
     }
 }
 private void Views_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
 {
     if (e.Action != NotifyCollectionChangedAction.Remove || e.Action != NotifyCollectionChangedAction.Replace)
     {
         return;
     }
     foreach (var removedView in e.OldItems)
     {
         MvvmHelpers.ViewAndViewModelAction <IDisposable>(removedView, d => d.Dispose());
     }
 }
Exemple #19
0
 private void Views_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
 {
     if (e.Action == NotifyCollectionChangedAction.Remove)
     {
         Action <IDisposable> DisposeCaller = d => d.Dispose();
         foreach (var i in e.OldItems)
         {
             MvvmHelpers.ViewAndViewModelAction(i, DisposeCaller);
         }
     }
 }
        private void Back()
        {
            this.KeepAlive = false;
            // find view by region
            var view = this.RegionManager.Regions["MainRegion"]
                       .ActiveViews
                       .First(x => MvvmHelpers.GetImplementerFromViewOrViewModel <ToDoDetailControlViewModel>(x) == this);

            // deactive view
            this.RegionManager.Regions["MainRegion"].Deactivate(view);

            this.RegionManager.RequestNavigate("MainRegion", nameof(ToDoListControlView));
        }
Exemple #21
0
 public BViewModel()
 {
     this.CloseCommand = new DelegateCommand(() =>
     {
         this.KeepAlive = false;
         // find view by region
         var view = this.RegionManager.Regions["MainRegion"]
                    .ActiveViews
                    .Where(x => MvvmHelpers.GetImplementerFromViewOrViewModel <BViewModel>(x) == this)
                    .First();
         // deactive view
         this.RegionManager.Regions["MainRegion"].Deactivate(view);
     });
 }
        public virtual void ShowShell <T>() where T : Window
        {
            IRegionManager regionManager = new RegionManager();

            var window = locator.GetInstance <T>();

            RegionManager.SetRegionManager(window, regionManager);

            // try to Set IRegionManagerAware for Shell ViewModel
            MvvmHelpers.ViewAndViewModelAction <IRegionManagerAware>(window, v => v.RegionManager = regionManager);

            InitializeShell(window);

            window.Show();
        }
Exemple #23
0
    private void ActiveViews_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action)
        {
        case NotifyCollectionChangedAction.Add:
            Action <IRegionManagerAware> setRegionManager = x => x.RegionManager = this.Region.RegionManager;
            MvvmHelpers.ViewAndViewModelAction(e.NewItems[0], setRegionManager);
            break;

        case NotifyCollectionChangedAction.Remove:
            Action <IRegionManagerAware> resetRegionManager = x => x.RegionManager = null;
            MvvmHelpers.ViewAndViewModelAction(e.OldItems[0], resetRegionManager);
            break;
        }
    }
Exemple #24
0
        // Methods.
        /// <summary>
        /// Displays the child FrameworkElement and collects results for <see cref="IInteractionRequest"/>.
        /// </summary>
        /// <param name="parameter"></param>
        protected override void Invoke(object parameter)
        {
            var args = parameter as InteractionRequestedEventArgs;

            if (args == null)
            {
                return;
            }

            // Add specified framework element to the current window.
            var window = Window.GetWindow(AssociatedObject);

            // Create a DockPanel that will act as a shadow for the specified framework element. It will also make the framework element "modal" by blocking off the rest of the window as long as the framework element is active.
            var backgroundElement = new DockPanel {
                Background = new SolidColorBrush(Color.FromArgb(90, 0, 0, 0)), VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch
            };

            backgroundElement.SetValue(Grid.ColumnSpanProperty, 20);
            backgroundElement.SetValue(Grid.RowSpanProperty, 20);

            // Find the first grid in the window,- works well enough for my purpose. One could modify this so that it accepts a name and/or type, so that one can specify individual parts of a view.
            Grid grid = window.FindElement <Grid>("");

            grid.Children.Add(backgroundElement);

            // If we haven't specified any content to show, alert the programmer.
            if (FrameworkElementContent == null)
            {
                throw new Exception("No FrameworkElement has been specified as dialog content.");
            }
            backgroundElement.Children.Add(FrameworkElementContent);

            Action <IInteractionRequestAware> setNotificationAndClose = (iira) =>
            {
                iira.Notification      = args.Context;
                iira.FinishInteraction = () =>
                {
                    // Remove the child FrameworkElement (the dialog) and execute the callback method.
                    backgroundElement.Children.Remove(FrameworkElementContent);
                    grid.Children.Remove(backgroundElement);
                    args.Callback();
                };
            };

            MvvmHelpers.ViewAndViewModelAction(FrameworkElementContent, setNotificationAndClose);
        }
        protected virtual void ViewsCollectionChanged(object sender, NotifyCollectionChangedEventArgs eventArgs)
        {
            //Eventの種類を確認
            switch (eventArgs.Action)
            {
            case NotifyCollectionChangedAction.Remove:
            case NotifyCollectionChangedAction.Replace: {
                foreach (object oldView in eventArgs.OldItems)
                {
                    //ViewからViewModelを取り出して、Disposeする
                    MvvmHelpers.ViewAndViewModelAction <IDisposable>(oldView, d => d.Dispose());
                }

                break;
            }
            }
        }
        /// <summary>
        /// Provides a new item for the region based on the supplied candidate target contract name.
        /// </summary>
        /// <param name="candidateTargetContract">The target contract to build.</param>
        /// <returns>An instance of an item to put into the <see cref="IRegion"/>.</returns>
        protected virtual object CreateNewRegionItem(string candidateTargetContract)
        {
            object newRegionItem;

            try
            {
                newRegionItem = _container.Resolve <object>(candidateTargetContract);
                MvvmHelpers.AutowireViewModel(newRegionItem);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException(
                          string.Format(CultureInfo.CurrentCulture, Resources.CannotCreateNavigationTarget, candidateTargetContract),
                          e);
            }
            return(newRegionItem);
        }
        private void ToDetail(TodoDetailData detailInfo)
        {
            this.KeepAlive = false;
            //TODO:情報残るようなら以下のコメントを消す
            // find view by region
            var view = RegionManager.Regions["MainRegion"]
                       .ActiveViews
                       .First(x => MvvmHelpers.GetImplementerFromViewOrViewModel <ToDoListControlViewModel>(x) == this);

            // deactive view
            this.RegionManager.Regions["MainRegion"].Deactivate(view);
            NavigationParameters param = new NavigationParameters();

            param.Add("SelectedDetailItem", detailInfo);

            this.RegionManager.RequestNavigate("MainRegion", nameof(ToDoDetailControlView), param);
        }
        private static bool ShouldKeepAlive(object inactiveView)
        {
            IRegionMemberLifetime lifetime = MvvmHelpers.GetImplementerFromViewOrViewModel <IRegionMemberLifetime>(inactiveView);

            if (lifetime != null)
            {
                return(lifetime.KeepAlive);
            }

            RegionMemberLifetimeAttribute lifetimeAttribute = GetItemOrContextLifetimeAttribute(inactiveView);

            if (lifetimeAttribute != null)
            {
                return(lifetimeAttribute.KeepAlive);
            }

            return(true);
        }
        protected override IRegion CreateRegion(DependencyObject targetElement, string regionName)
        {
            if (targetElement == null)
            {
                throw new ArgumentNullException(nameof(targetElement));
            }

            IRegionManager regionManager = FindRegionManagerForScope(targetElement);

            if (ContainsRegionWithName(regionManager, regionName))
            {
                regionManager = CreateRegionManagerForScope(targetElement);
            }

            MvvmHelpers.ViewAndViewModelAction <IRegionManagerAware>(targetElement, v => v.RegionManager = regionManager);

            return(base.CreateRegion(targetElement, regionName));
        }
Exemple #30
0
        /// <summary>
        /// Checks if the WindowContent or its DataContext implements <see cref="IInteractionRequestAware"/>.
        /// If so, it sets the corresponding value.
        /// Also, if WindowContent does not have a RegionManager attached, it creates a new scoped RegionManager for it.
        /// </summary>
        /// <param name="notification">The notification to be set as a DataContext in the HostWindow.</param>
        /// <param name="wrapperWindow">The HostWindow</param>
        protected virtual void PrepareContentForWindow(INotification notification, Window wrapperWindow)
        {
            if (this.WindowContent == null)
            {
                return;
            }

            // We set the WindowContent as the content of the window.
            wrapperWindow.Content = this.WindowContent;

            Action <IInteractionRequestAware> setNotificationAndClose = (iira) =>
            {
                iira.Notification      = notification;
                iira.FinishInteraction = () => wrapperWindow.Close();
            };

            MvvmHelpers.ViewAndViewModelAction(this.WindowContent, setNotificationAndClose);
        }