/// <summary>
    /// Show the required dialog.
    /// </summary>
    /// <typeparam name="TResult">The type of result to return.</typeparam>
    /// <param name="viewModel">The view model ascociated with the view.</param>
    public async Task <TResult> ShowDialog <TResult>(DialogViewModel <TResult> viewModel)
    {
        // Locate the ascociated view.
        var viewType = ViewLocator.LocateTypeForModelType(viewModel.GetType(), null, null);
        var dialog   = (BaseMetroDialog)Activator.CreateInstance(viewType);

        if (dialog == null)
        {
            throw new InvalidOperationException(
                      String.Format("The view {0} belonging to view model {1} " +
                                    "does not inherit from {2}",
                                    viewType,
                                    viewModel.GetType(),
                                    typeof(BaseMetroDialog)));
        }
        dialog.DataContext = viewModel;
        // Show the metro window.
        MetroWindow firstMetroWindow = Application.Current.Windows.OfType <MetroWindow>().First();
        await firstMetroWindow.ShowMetroDialogAsync(dialog);

        TResult result = await viewModel.Task;
        await firstMetroWindow.HideMetroDialogAsync(dialog);

        return(result);
    }
示例#2
0
        public static void NavigateToViewModel(this INavigationService navigationService, Type viewModel)
        {
            var viewType = ViewLocator.LocateTypeForModelType(viewModel, null, null);

            var packUri = ViewLocator.DeterminePackUriFromType(viewModel, viewType);

            var uri = new Uri(packUri, UriKind.Relative);

            navigationService.Navigate(uri);
        }
示例#3
0
        public void NavigateToViewModel(Type viewModel, string context, object extraData = null)
        {
            var viewType = ViewLocator.LocateTypeForModelType(viewModel, null, context);

            var packUri = ViewLocator.DeterminePackUriFromType(viewModel, viewType);

            var uri = new Uri(packUri, UriKind.Relative);

            frame.Navigate(uri, extraData);
        }
        public void NavigateToViewModel(Type viewModel)
        {
            var viewType = ViewLocator.LocateTypeForModelType(viewModel, null, null);

            var packUri = ViewLocator.DeterminePackUriFromType(viewModel, viewType);

            var uri = new Uri(packUri, UriKind.Relative);

            frame.Navigate(uri);
        }
示例#5
0
        public void Navigate(Type viewModelType, Dictionary <string, object> parameter, string context)
        {
            Type sourcePageType = ViewLocator.LocateTypeForModelType(viewModelType, null, context);

            if (sourcePageType == null)
            {
                throw new InvalidOperationException($"No view was found for {viewModelType.FullName}. See the log for searched views.");
            }

            this._frame.Navigate(sourcePageType, parameter);
        }
示例#6
0
        public void Check_view_binding()
        {
            var ignore     = new[] { typeof(BaseShell), typeof(BaseScreen), typeof(BaseScreen2) };
            var viewModels = typeof(AppBootstrapper).Assembly.GetTypes()
                             .Where(t => !t.IsAbstract && !t.IsInterface && typeof(IScreen).IsAssignableFrom(t) && !ignore.Contains(t));

            foreach (var type in viewModels)
            {
                Assert.IsNotNull(ViewLocator.LocateTypeForModelType(type, null, null), type.ToString());
            }
        }
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            var viewType = ViewLocator.LocateTypeForModelType(item.GetType(), null, null);

            if (viewType != null)
            {
                if (viewType.IsSubclassOf(typeof(BrowserExpander)) == true)
                {
                    var dataTemplate = new DataTemplate();
                    var element      = new FrameworkElementFactory(viewType);
                    element.SetBinding(BrowserExpander.HeaderProperty, new Binding("DisplayName"));
                    element.SetBinding(BrowserExpander.IsExpandedProperty, new Binding()
                    {
                        Path   = new PropertyPath(BrowserItemsControl.IsExpandedProperty),
                        Source = container,
                        Mode   = BindingMode.TwoWay,
                    });
                    element.SetBinding(Bind.ModelProperty, new Binding());
                    element.AddHandler(BrowserExpander.ExpandedEvent, new RoutedEventHandler(BrowserExpander_RoutedEventHandler));
                    element.AddHandler(BrowserExpander.CollapsedEvent, new RoutedEventHandler(BrowserExpander_RoutedEventHandler));
                    dataTemplate.VisualTree = element;
                    return(dataTemplate);
                }
                else
                {
                    var dataTemplate = new DataTemplate();
                    var element      = new FrameworkElementFactory(typeof(BrowserExpander));
                    element.SetBinding(BrowserExpander.HeaderProperty, new Binding("DisplayName"));
                    element.SetBinding(BrowserExpander.IsExpandedProperty, new Binding()
                    {
                        Path   = new PropertyPath(BrowserItemsControl.IsExpandedProperty),
                        Source = container,
                        Mode   = BindingMode.TwoWay,
                    });
                    element.AddHandler(BrowserExpander.ExpandedEvent, new RoutedEventHandler(BrowserExpander_RoutedEventHandler));
                    element.AddHandler(BrowserExpander.CollapsedEvent, new RoutedEventHandler(BrowserExpander_RoutedEventHandler));
                    var contentElement = new FrameworkElementFactory(viewType);
                    contentElement.SetBinding(Bind.ModelProperty, new Binding());
                    element.AppendChild(contentElement);
                    dataTemplate.VisualTree = element;
                    return(dataTemplate);
                }
            }

            return(base.SelectTemplate(item, container));

            void BrowserExpander_RoutedEventHandler(object sender, RoutedEventArgs e)
            {
                if (sender is BrowserExpander expander)
                {
                    BrowserItemsControl.SetIsExpanded(container, expander.IsExpanded);
                }
            }
        }
示例#8
0
        private void NavigateToViewModel(object viewModel, object parameter)
        {
            _viewModel = viewModel;

            var viewType = ViewLocator.LocateTypeForModelType(_viewModel.GetType(), null, null);

            BackStack.Clear();

            base.Navigate(viewType, parameter);

            _viewModel = null;
        }
示例#9
0
        static Type FindProxy(Func <Type, DependencyObject, object, Type> fallback,
                              Type modelType, DependencyObject displayLocation, object context)
        {
            var proxy = modelType.GetCustomAttribute <ProxyModelAttribute>();

            if (proxy != null && proxy.Type != modelType)
            {
                return(ViewLocator.LocateTypeForModelType(proxy.Type, displayLocation, context));
            }
            var ret = fallback(modelType, displayLocation, context);

            return(ret);
        }
示例#10
0
        /// <summary>
        /// Builds the URI.
        /// </summary>
        /// <returns>A uri constructed with the current configuration information.</returns>
        public Uri BuildUri()
        {
            var viewType = ViewLocator.LocateTypeForModelType(typeof(TViewModel), null, null);

            if (viewType == null)
            {
                throw new Exception(string.Format("No view was found for {0}. See the log for searched views.", typeof(TViewModel).FullName));
            }

            var packUri = ViewLocator.DeterminePackUriFromType(typeof(TViewModel), viewType);
            var qs      = BuildQueryString();

            return(new Uri("/Shell" + packUri + qs, UriKind.Relative));
        }
示例#11
0
        private void InitializeViewLocator(IBootstrapper bootstrapper)
        {
            //overriden for performance reasons (Assembly caching)
            ViewLocator.LocateTypeForModelType = (modelType, displayLocation, context) =>
            {
                var viewTypeName = modelType.FullName.Substring(0, modelType.FullName.IndexOf("`") < 0
                    ? modelType.FullName.Length
                    : modelType.FullName.IndexOf("`")
                                                                ).Replace("Model", string.Empty);

                if (context != null)
                {
                    viewTypeName = viewTypeName.Remove(viewTypeName.Length - 4, 4);
                    viewTypeName = viewTypeName + "." + context;
                }

                Type viewType;
                if (!_typedic.TryGetValue(viewTypeName, out viewType))
                {
                    _typedic[viewTypeName] = viewType = (from assembly in bootstrapper.Assemblies
                                                         from type in assembly
#if NET || NETCORE
                                                         .GetExportedTypes()
#endif
#if WINDOWS_UWP || NETFX_CORE
                                                         .DefinedTypes
#endif
                                                         where type.FullName == viewTypeName
                                                         select type
#if WINDOWS_UWP || NETFX_CORE
                                                         .AsType()
#endif
                                                         ).FirstOrDefault();
                }

                return(viewType);
            };
            ViewLocator.LocateForModelType = (modelType, displayLocation, context) =>
            {
                var viewType = ViewLocator.LocateTypeForModelType(modelType, displayLocation, context);

                return(viewType == null
                    ? new TextBlock
                {
                    Text = $"Cannot find view for\nModel: {modelType}\nContext: {context} ."
                }
                    : ViewLocator.GetOrCreateViewType(viewType));
            };
        }
        protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
        {
            Type vmType = item.GetType();

            DataTemplate dataTemplate;

            if (!_selectorDict.TryGetValue(vmType, out dataTemplate))
            {
                Type viewType = ViewLocator.LocateTypeForModelType(vmType, null, null);

                dataTemplate = new DataTemplate(viewType);

                _selectorDict.Add(vmType, dataTemplate);
            }

            return(dataTemplate);
        }
示例#13
0
        public async Task <TReturn> ShowDialog <TViewModel, TReturn>(TViewModel rootModel)
            where TViewModel : class, IScreen
        {
            var viewType = ViewLocator.LocateTypeForModelType(typeof(TViewModel), null, null);
            var view     = (FrameworkElement)Activator.CreateInstance(viewType);

            ViewModelBinder.Bind(rootModel, view, null);
            view.DataContext = rootModel;

            conductor.ActivateItem(rootModel);
            var returnValue = await DialogHost.Show(view, OnDialogClosing);

            if (returnValue == null)
            {
                return(default(TReturn));
            }

            return((TReturn)returnValue);
        }
示例#14
0
        public async Task ShowDialogAsync(DialogViewModelBase viewModel)
        {
            var viewType = ViewLocator.LocateTypeForModelType(viewModel.GetType(), null, null);
            var dialog   = (BaseMetroDialog)Activator.CreateInstance(viewType);

            if (dialog == null)
            {
                throw new InvalidOperationException(
                          $"The view {viewType} belonging to view model {viewModel.GetType()} " +
                          $"does not inherit from {typeof(BaseMetroDialog)}");
            }
            dialog.DataContext = viewModel;

            MetroWindow firstMetroWindow =
                Application.Current.Windows.OfType <MetroWindow>().First();
            await firstMetroWindow.ShowMetroDialogAsync(dialog);

            await viewModel.Task;
            await firstMetroWindow.HideMetroDialogAsync(dialog);
        }
示例#15
0
        private Type LocateTypeForModelType(Type vmType, DependencyObject location, object context)
        {
            var attribute = vmType.GetCustomAttributes(typeof(ViewAttribute), true).OfType<ViewAttribute>().FirstOrDefault();
            if (attribute != null)
            {
                return Type.GetType(attribute.ViewTypeName);
            }

            var viewType = this.locateTypeForModelType(vmType, location, context);

            if (viewType == null)
            {
                Type baseType = vmType.BaseType;
                if (baseType.Name.EndsWith("ViewModel") == true)
                {
                    return ViewLocator.LocateTypeForModelType(baseType, location, context);
                }
            }

            return viewType;
        }
示例#16
0
        private async Task NavigateWithFrame(Type viewModelType, object parameter)
        {
            if (_tcs != null)
            {
                throw new InvalidOperationException(StringResources.PendingNavigation);
            }

            try
            {
                var viewType = ViewLocator.LocateTypeForModelType(viewModelType, null, null);
                if (viewType == null)
                {
                    throw new Exception(string.Format(StringResources.ViewNotFound, viewModelType.FullName));
                }

                if (!await GuardAsync(viewModelType))
                {
                    throw new TaskCanceledException();
                }

                var prepareAction = parameter as Func <object, Task>;
                _tcs = new TaskCompletionSource <bool>();
                var currentViewModel = ActiveViewModel as INavigationTarget;
                currentViewModel.SaveState(_frame);

                if (!_frameAdapter.Navigate(viewType, parameter))
                {
                    _tcs.TrySetCanceled();
                }

                await currentViewModel.OnNavigatedFromAsync(prepareAction == null?parameter : null);

                await _tcs.Task;
            }
            finally
            {
                _tcs = null;
            }
        }
示例#17
0
        /// <summary>
        /// Creates an instance of the <see cref="LogoFXApplication{TRootViewModel}"/>
        /// </summary>
        /// <param name="bootstrapper">The app bootstrapper.</param>
        /// <param name="viewFirst">Use true to enable built-in navigation, false otherwise. The default value is true.</param>
        public LogoFXApplication(
            BootstrapperBase bootstrapper,
            bool viewFirst = true)
        {
            Initialize();

            bootstrapper
            .Use(new RegisterCompositionModulesMiddleware <BootstrapperBase>())
            .Use(new RegisterRootViewModelMiddleware <BootstrapperBase, TRootViewModel>())
            .Initialize();

            _dependencyRegistrator = bootstrapper.Registrator;

            if (viewFirst)
            {
                var viewType = ViewLocator.LocateTypeForModelType(typeof(TRootViewModel), null, null);
                DisplayRootView(viewType);
            }
            else
            {
                //Default navigation does not work in this case
                DisplayRootViewFor <TRootViewModel>();
            }
        }
        protected override void Configure()
        {
            var catalog = new AggregateCatalog();

            foreach (var item in AssemblySource.Instance)
            {
                catalog.Catalogs.Add(new AssemblyCatalog(item));
            }

            this.container = new CompositionContainer(catalog);

            var batch         = new CompositionBatch();
            var windowManager = new AppWindowManager();

            AppMessageBox.WindowManager = ModalDialogBase.WindowManager = windowManager;

            batch.AddExportedValue <IWindowManager>(windowManager);
            batch.AddExportedValue <IEventAggregator>(new EventAggregator());
            batch.AddExportedValue <IAppConfiguration>(this.configs);
            batch.AddExportedValue <IServiceProvider>(this);
            batch.AddExportedValue <ICompositionService>(this.container);

            foreach (var item in this.GetParts())
            {
                var contractName = AttributedModelServices.GetContractName(item.Item1);
                var typeIdentity = AttributedModelServices.GetTypeIdentity(item.Item1);
                batch.AddExport(new Export(contractName, new Dictionary <string, object>
                {
                    {
                        "ExportTypeIdentity",
                        typeIdentity
                    }
                }, () => item.Item2));
            }
            this.container.Compose(batch);
            this.container.SatisfyImportsOnce(windowManager);

            var defaultLocateForView = ViewModelLocator.LocateForView;

            ViewModelLocator.LocateForView = (view) =>
            {
                object viewModel = defaultLocateForView(view);
                if (viewModel != null)
                {
                    return(viewModel);
                }

                if (TypeDescriptor.GetAttributes(view)[typeof(ModelAttribute)] is ModelAttribute attr)
                {
                    if (attr.ModelType.IsInterface == true)
                    {
                        return(this.GetInstance(attr.ModelType, null));
                    }
                    return(TypeDescriptor.CreateInstance(null, attr.ModelType, null, null));
                }

                return(viewModel);
            };

            var defaultLocateTypeForModelType = ViewLocator.LocateTypeForModelType;

            ViewLocator.LocateTypeForModelType = (vmType, location, context) =>
            {
                var attribute = vmType.GetCustomAttributes(typeof(ViewAttribute), true).OfType <ViewAttribute>().FirstOrDefault();
                if (attribute != null)
                {
                    return(Type.GetType(attribute.ViewTypeName));
                }

                var viewType = defaultLocateTypeForModelType(vmType, location, context);

                if (viewType == null)
                {
                    Type baseType = vmType.BaseType;
                    if (baseType.Name.EndsWith("ViewModel") == true)
                    {
                        return(ViewLocator.LocateTypeForModelType(baseType, location, context));
                    }
                }

                return(viewType);
            };

            var defaultLocateForModel = ViewLocator.LocateForModel;

            ViewLocator.LocateForModel = (model, displayLocation, context) =>
            {
                //IViewAware viewAware = model as IViewAware;
                //if (viewAware != null)
                //{
                //    UIElement uIElement = viewAware.GetView(context) as UIElement;
                //    if (uIElement != null)
                //    {
                //        Window window = uIElement as Window;
                //        if (window == null || (!window.IsLoaded && !(new System.Windows.Interop.WindowInteropHelper(window).Handle == IntPtr.Zero)))
                //        {
                //            //ViewLocator.Log.Info("Using cached view for {0}.", new object[]
                //            //{
                //            //    model
                //            //});
                //            return uIElement;
                //        }
                //    }
                //}
                var view = defaultLocateForModel(model, displayLocation, context);

                if (view != null && view.GetType().GetCustomAttributes <ExportAttribute>(true).Any() == false)
                {
                    this.container.SatisfyImportsOnce(view);
                }

                return(view);
            };
        }
示例#19
0
        public void Init(bool failfast)
        {
            MessageBus.Current.RegisterScheduler <string>(ImmediateScheduler.Instance, "db");

            ConventionManager.Singularize = s => {
                if (s == "Taxes")
                {
                    return("Tax");
                }
                if (s == "Value")
                {
                    return(s);
                }
                return(s.Singularize() ?? s);
            };
            //нужно затем что бы можно было делать модели без суффикса ViewModel
            //достаточно что бы они лежали в пространстве имен ViewModels
            ViewLocator.NameTransformer.AddRule(
                @"(?<nsbefore>([A-Za-z_]\w*\.)*)(?<subns>ViewModels\.)"
                + @"(?<nsafter>([A-Za-z_]\w*\.)*)(?<basename>[A-Za-z_]\w*)"
                + @"(?!<suffix>ViewModel)$",
                "${nsbefore}Views.${nsafter}${basename}View");
            //что бы не нужно было использовать суффиксы View и ViewModel
            ViewLocator.NameTransformer.AddRule(
                @"(?<nsbefore>([A-Za-z_]\w*\.)*)(?<subns>ViewModels\.)"
                + @"(?<nsafter>([A-Za-z_]\w*\.)*)(?<basename>[A-Za-z_]\w*)"
                + @"(?!<suffix>)$",
                "${nsbefore}Views.${nsafter}${basename}");

            //безумие - сам по себе Caliburn если не найден view покажет текст Cannot find view for
            //ни исключения ни ошибки в лог
            ViewLocator.LocateForModelType = (modelType, displayLocation, context) => {
                var viewType = ViewLocator.LocateTypeForModelType(modelType, displayLocation, context);
                if (viewType == null)
                {
                    if (failfast)
                    {
                        throw new Exception(String.Format("Не удалось найти вид для отображения {0}", modelType));
                    }
                    else
                    {
                        log.ErrorFormat("Не удалось найти вид для отображения {0}", modelType);
                    }
                }

                return(viewType == null
                                                        ? new TextBlock()
                                                        : ViewLocator.GetOrCreateViewType(viewType));
            };

            Conventions.Register();
            SaneCheckboxEditor.Register();
            NotifyValueSupport.Register();

            var customPropertyBinders = new Action <IEnumerable <FrameworkElement>, Type>[] {
                EnabledBinder.Bind,
                VisibilityBinder.Bind,
            };
            var customBinders = new Action <Type, IEnumerable <FrameworkElement>, List <FrameworkElement> >[] {
                //сначала должен обрабатываться поиск и только потом переход
                SearchBinder.Bind,
                NavBinder.Bind,
                EnterBinder.Bind,
            };

            var defaultBindProperties = ViewModelBinder.BindProperties;
            var defaultBindActions    = ViewModelBinder.BindActions;
            var defaultBind           = ViewModelBinder.Bind;

            ViewModelBinder.Bind = (viewModel, view, context) => {
                if ((bool)view.GetValue(ViewModelBinder.ConventionsAppliedProperty))
                {
                    return;
                }

                defaultBind(viewModel, view, context);
                ContentElementBinder.Bind(viewModel, view, context);
                Commands.Bind(viewModel, view, context);
                var baseScreen = viewModel as BaseScreen;
                //этот метод будет вызваться каждый раз при активации\деактивации формы
                //что бы избежать множественных подписок
                if (baseScreen != null && !baseScreen.ResultsSink.HasObservers)
                {
                    baseScreen.ResultsSink
                    .CatchSubscribe(r => Coroutine.BeginExecute(new List <IResult> {
                        r
                    }.GetEnumerator(), new ActionExecutionContext {
                        View = view
                    }), baseScreen.CloseCancellation);
                }
                var baseShell = viewModel as BaseShell;
                if (baseShell != null && !baseShell.ResultsSink.HasObservers)
                {
                    baseShell.ResultsSink
                    .CatchSubscribe(r => Coroutine.BeginExecute(new List <IResult> {
                        r
                    }.GetEnumerator(), new ActionExecutionContext {
                        View = view
                    }), baseShell.CancelDisposable);
                }
            };

            ViewModelBinder.BindProperties = (elements, type) => {
                foreach (var binder in customPropertyBinders)
                {
                    binder(elements, type);
                }
                return(defaultBindProperties(elements, type));
            };

            ViewModelBinder.BindActions = (elements, type) => {
                var binded = defaultBindActions(elements, type).ToList();

                foreach (var binder in customBinders)
                {
                    binder(type, elements, binded);
                }
                return(elements);
            };
        }