public SelectAudioFilesViewModel(ViewLocator locator, SharedModel sharedModel)
 {
     _sharedModel = sharedModel;
     _locator = locator;
     CanSwitchToNewMode = true;
     SelectFilesCommand = new RelayCommand(SelectFiles);
     SwitchToNewModeCommand = new RelayCommand(SwitchToNewMode);
 }
 public void DefaultViewLocator() {
     Assert.IsNotNull(ViewLocator.Instance);
     Assert.AreSame(ViewLocator.Instance, ViewLocator.Default);
     ViewLocator vl = new ViewLocator(new Assembly[] { });
     ViewLocator.Default = vl;
     Assert.AreSame(vl, ViewLocator.Default);
     ViewLocator.Default = null;
     Assert.AreSame(ViewLocator.Instance, ViewLocator.Default);
 }
        public IScriptPackContext GetContext()
        {
            var fileSystem = new FileSystem();
            var threadManager = new ThreadManager();
            var xamlLoader = new XamlLoader(fileSystem);
            var viewLocator = new ViewLocator(fileSystem);
            var applicationLauncher = new ApplicationLauncher();

            return new Wpf(applicationLauncher, viewLocator, xamlLoader, threadManager);
        }
 public AlbumDetailsViewModel(IZuneDatabaseReader dbReader,
                         ViewLocator locator,
                         SharedModel sharedModel)
 {
     _dbReader = dbReader;
     _locator = locator;
     _sharedModel = sharedModel;
     LinkCommand = new RelayCommand(LinkAlbum);
     RefreshCommand = new RelayCommand(RefreshAlbum);
     DelinkCommand = new RelayCommand(DelinkAlbum);
 }
            public void ShouldReturnViewNameIfFileExists()
            {
                var fileSystem = new Mock<IFileSystem>();
                fileSystem.SetupGet(x => x.CurrentDirectory).Returns("C:\\");
                fileSystem.Setup(x => x.FileExists("C:\\TestView.xaml")).Returns(true);

                var viewLocator = new ViewLocator(fileSystem.Object);

                var result = viewLocator.LocateViewFor("TestViewModel");

                result.ShouldEqual("C:\\TestView.xaml");
            }
            public void ShouldReturnCorrectFileName(string viewModel, string fileName)
            {
                var fileSystem = new Mock<IFileSystem>();
                fileSystem.SetupGet(x => x.CurrentDirectory).Returns(string.Empty);
                fileSystem.Setup(x => x.FileExists(It.IsAny<string>())).Returns(true);

                var viewLocator = new ViewLocator(fileSystem.Object);

                var result = viewLocator.LocateViewFor(viewModel);

                result.ShouldEqual(fileName);
            }
        public ApplicationViewModel(IZuneDatabaseReader dbReader,
                                    SafeObservableCollection<AlbumDetailsViewModel> albums,
                                    ViewLocator locator,
                                    IKernel kernel,
                                    ApplicationView av)
        {
            _dbReader = dbReader;
            _albums = albums;
            _viewLocator = locator;
            _kernel = kernel;

            //register for notification messages
            Messenger.Default.Register<ErrorMessage>(this, Notifications.Add);
            Messenger.Default.Register<UserControl>(this, (view) => { CurrentPage = view; });
        }
        public WebAlbumListViewModel(SafeObservableCollection<AlbumDetailsViewModel> albums,
                                     ViewLocator locator)
        {
            _albums = albums;
            _albums.CollectionChanged += AlbumsCollectionChanged;
            _cvs = new CollectionViewSource();
            _cvs.Source = albums;
            _cvs.Filter += CvsFilter;

            _locator = locator;

            this.LoadFromZuneWebsiteCommand = new RelayCommand(LoadFromZuneWebsite);
            this.SwitchToClassicModeCommand = new RelayCommand(SwitchToClassicMode);
            this.SortCommand = new RelayCommand(Sort);
            this.SearchCommand = new RelayCommand<string>(Search);
            this.SortOrder = Settings.Default.SortOrder;
        }
Esempio n. 9
0
        protected override void Configure()
        {
            ConfigureTitleBar();

            ViewModelLocator.AddNamespaceMapping("Demo.App.Views", "Demo.Core.ViewModels");
            ViewLocator.AddNamespaceMapping("Demo.Core.ViewModels", "Demo.App.Views");

            container = new WinRTContainer();
            container.RegisterWinRTServices();

            container.Singleton <ISettingsService, StorageSettingsService>();
            container.Singleton <IRepositoryService, RepositoryService>();
            container.Singleton <IIssuesService, IssuesService>();

            container.Instance(CreateClient());

            container
            .ViewModel <ShellViewModel>()
            .ViewModel <MenuViewModel>()
            .ViewModel <RepositoryDetailsViewModel>()
            .ViewModel <IssuesListViewModel>();
        }
        private static ViewModelPair ForViewModel(Type viewModelType, object parameters = null)
        {
            try
            {
                var view = ViewLocator.LocateForModelType(viewModelType, null, null) as Page;
                if (view == null)
                {
                    throw new NotSupportedException(String.Format("{0} does not inherit from {1}.", view.GetType(), typeof(Page)));
                }

                var viewModel = ViewModelLocator.LocateForView(view) as ViewModelBase;
                ViewModelBinder.Bind(viewModel, view, parameters);
                TrySetParameters(viewModel, parameters);
                return(new ViewModelPair {
                    View = view, ViewModel = viewModel
                });
            }
            catch (Exception e)
            {
                throw;
            }
        }
Esempio n. 11
0
        protected override void Configure()
        {
            ViewModelLocator.AddNamespaceMapping("Spending.App.Windows.Views", "Spending.Core.ViewModels");
            ViewLocator.AddNamespaceMapping("Spending.Core.ViewModels", "Spending.App.Windows.Views");

            container = new WinRTContainer();
            container.RegisterWinRTServices();

            container
            .Instance <IMobileServiceClient>(new MobileServiceClient("https://spending.azurewebsites.net"));

            container
            .Singleton <IAuthenticationService, AuthenticationService>()
            .Singleton <IApplicationNavigationService, ApplicationNavigationService>()
            .Singleton <IExpenseService, ExpenseService>()
            .Singleton <INotificationsService, NotificationsService>();

            container
            .PerRequest <LoginViewModel>()
            .PerRequest <CurrentExpensesViewModel>()
            .PerRequest <AddExpenseViewModel>();
        }
        UIElement GetView(object viewModel)
        {
            if (viewModel == null)
            {
                return(null);
            }

            UIElement view = Children
                             .OfType <FrameworkElement>()
                             .FirstOrDefault(fe => ReferenceEquals(fe.DataContext, viewModel));

            if (view != null)
            {
                return(view);
            }

            var context = View.GetContext(this);

            view = ViewLocator.LocateForModel(viewModel, this, context);
            ViewModelBinder.Bind(viewModel, view, context);
            return(view);
        }
Esempio n. 13
0
        protected override void Configure()
        {
            // This configures the framework to map between MainViewModel and MainPage
            // Normally it would map between MainPageViewModel and MainPage
            var config = new TypeMappingConfiguration
            {
                IncludeViewSuffixInViewModelNames = false
            };

            ViewLocator.ConfigureTypeMappings(config);
            ViewModelLocator.ConfigureTypeMappings(config);

            _container = new WinRTContainer();
            _container.RegisterWinRTServices();

            _container.PerRequest <ShellViewModel>();
            _container.PerRequest <MainViewModel>();
            _container.PerRequest <CameraViewModel>();
            _container.PerRequest <ContentGridDetailViewModel>();
            _container.PerRequest <ContentGridViewModel>();
            _container.PerRequest <SettingsViewModel>();
        }
Esempio n. 14
0
        /// <summary>
        /// 展示对话框
        /// </summary>
        public static async Task <bool?> ShowDialogAsync <TViewModel>(this INavigationService navigationService) where TViewModel : Screen
        {
            Screen  viewModel = ResolveMediator.Resolve <TViewModel>();
            Element view      = ViewLocator.LocateForModelType(typeof(TViewModel), null, null);
            Dialog  dialog    = view as Dialog;

            #region # 验证

            if (dialog == null)
            {
                throw new NotSupportedException($"\"{view.GetType()}\"未继承\"{typeof(Dialog)}\"!");
            }

            #endregion

            ViewModelBinder.Bind(viewModel, view, null);

            NavigationPage navigationPage = ResolveMediator.Resolve <NavigationPage>();
            bool?          result         = await navigationPage.Navigation.ShowPopupAsync(dialog);

            return(result);
        }
Esempio n. 15
0
        public override void Dispatch(IViewContext viewContext, IEnumerable <DomainEvent> batch)
        {
            if (_purging)
            {
                return;
            }

            var cachedViewInstances = new Dictionary <string, TViewInstance>();

            var eventList = batch.ToList();

            if (!eventList.Any())
            {
                return;
            }

            foreach (var e in eventList)
            {
                if (!ViewLocator.IsRelevant <TViewInstance>(e))
                {
                    continue;
                }

                var viewIds = _viewLocator.GetAffectedViewIds(viewContext, e);

                foreach (var viewId in viewIds)
                {
                    var viewInstance = cachedViewInstances[viewId] = GetOrCreateViewInstance(viewId, cachedViewInstances);

                    _dispatcherHelper.DispatchToView(viewContext, e, viewInstance);
                }
            }

            FlushCacheToDatabase(cachedViewInstances);

            RaiseUpdatedEventFor(cachedViewInstances.Values);

            UpdatePersistentCache(eventList.Max(e => e.GetGlobalSequenceNumber()));
        }
Esempio n. 16
0
        protected override void Configure()
        {
            // This configures the framework to map between MainViewModel and MainPage
            // Normally it would map between MainPageViewModel and MainPage
            var config = new TypeMappingConfiguration
            {
                IncludeViewSuffixInViewModelNames = false
            };

            ViewLocator.ConfigureTypeMappings(config);
            ViewModelLocator.ConfigureTypeMappings(config);

            _container = new WinRTContainer();
            _container.RegisterWinRTServices();

            _container.PerRequest <MainViewModel>()
            .PerRequest <ServerViewModel>()
            .PerRequest <SettingViewModel>()
            .Singleton <AppService>();

            var appService = _container.GetInstance <AppService>();
        }
Esempio n. 17
0
        private static ContentPane CreateDockable(object rootModel, object context)
        {
            var view = EnsureDockWindow(ViewLocator.LocateForModel(rootModel, null, context));

            ViewModelBinder.Bind(rootModel, view, context);

            var haveDisplayName = rootModel as IHaveDisplayName;

            if (haveDisplayName != null && !ConventionManager.HasBinding(view, HeaderedContentControl.HeaderProperty))
            {
                Binding binding = new Binding("DisplayName")
                {
                    Mode = BindingMode.TwoWay
                };
                view.SetBinding(HeaderedContentControl.HeaderProperty, binding);
            }

            // ReSharper disable once ObjectCreationAsStatement
            new DockableWindowConductor(rootModel, view);

            return(view);
        }
        public static void ConfigureViewLocator()
        {
            ViewLocator.LocateForModelType = (modelType, displayLocation, context) =>
            {
                var useViewAttributes = modelType.GetCustomAttributes(typeof(UseViewAttribute), true)
                                        .Cast <UseViewAttribute>();

                Contract.Assert(useViewAttributes.Count() <= 1, "There can only be zero or one UseViewAttribute on a view model");

                string viewTypeName;

                if (useViewAttributes.Count() == 1)
                {
                    viewTypeName = string.Concat(modelType.Namespace.Substring(0, modelType.Namespace.IndexOf(".ViewModels")), ".Views.",
                                                 useViewAttributes.First().ViewName);
                }
                else
                {
                    viewTypeName = modelType.FullName.Replace("Model", string.Empty);
                    if (context != null)
                    {
                        viewTypeName = viewTypeName.Remove(viewTypeName.Length - 4, 4);
                        viewTypeName = viewTypeName + "." + context;
                    }
                }

                var viewType = (from assembly in AssemblySource.Instance
                                from type in assembly.GetExportedTypes()
                                where type.FullName == viewTypeName
                                select type).FirstOrDefault();

                return(viewType == null
                                        ? new TextBlock {
                    Text = string.Format("{0} not found.", viewTypeName)
                }
                                        : ViewLocator.GetOrCreateViewType(viewType));
            };
        }
Esempio n. 19
0
        public async void Upload(object arg)
        {
            try
            {
                IsUploading = true;

                if (Account.Equals(AppResources.SkyDriveNameText))
                {
                    await UploadToSkyDriveAsync(false);
                }

                if (Account.Equals(AppResources.SoundCloudNameText))
                {
                    await UploadToSoundCloudAsync();
                }

                if (NavigationService.CanGoBack)
                {
                    NavigationService.GoBack();
                }
            }
            catch (InvalidOperationException)
            {
                if (ShowMessage(string.Format(AppResources.AccountDisconnectedMessageText,
                                              Account), AppResources.AccountDisconnectedMessageCaption,
                                System.Windows.MessageBoxButton.OKCancel) == System.Windows.MessageBoxResult.OK)
                {
                    NavigationService.Navigate(ViewLocator.View("AccountSettings"));
                }

                IsUploading = false;
            }
            catch
            {
                IsUploading = false;
                ShowToast(AppResources.UploadFailedMessageCaption, string.Format(AppResources.UploadFailedMessageText, Account));
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Shows a popup at the current mouse position.
        /// </summary>
        /// <param name="rootModel">The root model.</param>
        /// <param name="context">The view context.</param>
        /// <param name="settings">The optional popup settings.</param>
        public virtual void ShowPopup(object rootModel, object context = null, IDictionary <string, object> settings = null)
        {
            var popup = this.CreatePopup(rootModel, settings);
            var view  = ViewLocator.LocateForModel(rootModel, popup, context);

            popup.Child = view;
            popup.SetValue(View.IsGeneratedProperty, true);

            ViewModelBinder.Bind(rootModel, popup, null);
            Caliburn.Micro.Action.SetTargetWithoutContext(view, rootModel);

            var activatable = rootModel as IActivate;

            activatable?.Activate();

            if (rootModel is IDeactivate deactivator)
            {
                popup.Closed += delegate { deactivator.Deactivate(true); };
            }

            popup.IsOpen = true;
            popup.CaptureMouse();
        }
Esempio n. 21
0
        protected override void Configure()
        {
            ViewModelLocator.AddNamespaceMapping("NDC.Build.App.UWP.Views", "NDC.Build.Core.ViewModels");
            ViewLocator.AddNamespaceMapping("NDC.Build.Core.ViewModels", "NDC.Build.App.UWP.Views");

            MessageBinder.SpecialValues.Add("$clickedItem", c => ((ItemClickEventArgs)c.EventArgs).ClickedItem);

            container = new WinRTContainer();

            container.RegisterWinRTServices();

            container
            .Singleton <ITeamServicesClient, OfflineTeamServicesClient>()
            .Singleton <IAuthenticationService, OfflineAuthenticationService>()
            .Singleton <IApplicationNavigationService, ApplicationNavigationService>()
            .Singleton <ICredentialsService, SettingsCredentialsService>()
            .Singleton <IDialogService, ContentDialogService>();

            container
            .PerRequest <LoginViewModel>()
            .PerRequest <ProjectsViewModel>()
            .PerRequest <BuildsViewModel>();
        }
Esempio n. 22
0
        protected override void OnStartup(StartupEventArgs e)
        {
            Dispatcher.UnhandledException += Dispatcher_UnhandledException;

            ViewLocator.RegisterViews(Resources, typeof(App).Assembly);

            _fusInterface = new FusApplicationInterface();
            _fusInterface.Start();

            Dispatcher.Hooks.DispatcherInactive += (_, __) => _fusInterface.CallIdle();
            base.OnStartup(e);

            // prepare for messages
            _fusInterface.GetGenericMessageInterface().MessageRequested += App_MessageRequested;

            Log.Logger = new LoggerConfiguration()
                         .Enrich.WithThreadId()
                         .MinimumLevel.Debug()
                         //.MinimumLevel.Information()
                         //.MinimumLevel.Override("Dicom", LogEventLevel.Warning)
                         .WriteTo.Console(outputTemplate: "[{Timestamp} {Level:u3}] [{SourceContext}] [tid:{ThreadId}] {Message:lj}{NewLine}{Exception}")
                         .CreateLogger();
        }
Esempio n. 23
0
            public void ClearsTheCache()
            {
                var viewLocator  = new ViewLocator();
                var resolvedType = viewLocator.ResolveView(typeof(PersonViewModel));

                Assert.IsNotNull(resolvedType);
                Assert.AreEqual(typeof(PersonView), resolvedType);

                // Clear the naming conventions (so it *must* come from the cache)
                viewLocator.NamingConventions.Clear();

                resolvedType = viewLocator.ResolveView(typeof(PersonViewModel));

                Assert.IsNotNull(resolvedType);
                Assert.AreEqual(typeof(PersonView), resolvedType);

                // Clear the cache, now it should break
                viewLocator.ClearCache();

                resolvedType = viewLocator.ResolveView(typeof(PersonViewModel));

                Assert.IsNull(resolvedType);
            }
Esempio n. 24
0
        public void NavigateToType(Type value)
        {
            if (value == null || !typeof(PageViewModel).IsAssignableFrom(value))
            {
                return;
            }
            if (_existingViewModels.TryGetValue(value, out var viewModel) &&
                _existingViews.TryGetValue(value, out var view))
            {
                ActivePage = view;
                ActivateItem(viewModel);
            }
            else
            {
                var vm = _resolver.Resolve <PageViewModel>(value);
                ActivePage = (PageView)ViewLocator.LocateForModel(vm, null, null);
                ViewModelBinder.Bind(vm, ActivePage, null);
                ActivateItem(vm);

                _existingViewModels.Add(value, vm);
                _existingViews.Add(value, ActivePage);
            }
        }
Esempio n. 25
0
        protected override void Configure()
        {
            //  configure container
            var builder = new ContainerBuilder();

            //  register view models
            builder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray())
            //  must be a type that ends with ViewModel
            .Where(type => type.Name.EndsWith("ViewModel"))
            //  must implement INotifyPropertyChanged (deriving from PropertyChangedBase will statisfy this)
            .Where(type => type.GetInterface(typeof(System.ComponentModel.INotifyPropertyChanged).Name) != null)
            //  registered as self
            .AsSelf()
            .PropertiesAutowired()
            //  always create a new one
            .InstancePerDependency();

            //  register views
            builder.RegisterAssemblyTypes(AssemblySource.Instance.ToArray())
            //  must be a type that ends with View
            .Where(type => type.Name.EndsWith("View"))
            //  registered as self
            .AsSelf()
            //  always create a new one
            .InstancePerDependency();

            //  register the single window manager for this container
            builder.Register <IWindowManager>(c => new WindowManager()).InstancePerLifetimeScope();
            //  register the single event aggregator for this container
            builder.Register <IEventAggregator>(c => new EventAggregator()).InstancePerLifetimeScope();

            ConfigureContainer(builder);

            Container = builder.Build();

            ViewLocator.AddSubNamespaceMapping("ViewModel", "View");
        }
        public ShellViewModel()
        {
            if (!Directory.Exists(ApplicationSettings.Instance.DiffDirectory))
            {
                Directory.CreateDirectory(ApplicationSettings.Instance.DiffDirectory);
            }
            var files = Directory.GetFiles(ApplicationSettings.Instance.DiffDirectory).ToList();

            files.ForEach(File.Delete);

            MenuView         = ViewLocator.GetSharedInstance <IMenuView>();
            MainView         = ViewLocator.GetSharedInstance <IRevisionHistoryView>();
            RepositoriesView = ViewLocator.GetSharedInstance <IRepositoriesView>();
            Container.RegisterInstance <ISourceControlController>();
            ChildWindowState = WindowState.Closed;

            Mediator.Subscribe <BeginBusyEvent>(text =>
            {
                IsBusy     = true;
                IsBusyText = (text ?? "").ToString();
            });
            Mediator.Subscribe <EndBusyEvent>(text => IsBusy = false);

            var showChildWindow = new Action <object>(repo =>
            {
                UiDispatcherService.InvokeAsync(() =>
                {
                    ChildWindowContent = ViewLocator.GetSharedInstance <IRepositoryEditorView>();
                    ChildWindowState   = WindowState.Open;
                });
            });

            Mediator.Subscribe <EditRepositoryEvent>(showChildWindow);
            Mediator.Subscribe <AddRepositoryEvent>(showChildWindow);

            Mediator.Subscribe <HideChildWindowEvent>(ignore => ChildWindowState = WindowState.Closed);
        }
    /// <summary>
    /// Show the required dialog.
    /// </summary>
    /// <param name="viewModel">The view model ascociated with the view.</param>
    public async Task ShowDialog(DialogViewModel 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);

        await viewModel.Task;
        await firstMetroWindow.HideMetroDialogAsync(dialog);
    }
Esempio n. 28
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>();
            }
        }
Esempio n. 29
0
        /// <inheritdoc />
        public Task NavigateToViewModelInstanceAsync <TViewModel>(TViewModel viewModel, bool animated = true)
        {
            Element element;

            try
            {
                element = ViewLocator.LocateForModelType(typeof(TViewModel), null, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
            var page = element as Page;

            if (page == null && !(element is ContentView))
            {
                throw new NotSupportedException(
                          $"{element.GetType()} does not inherit from either {typeof(Page)} or {typeof(ContentView)}.");
            }
            try
            {
                ViewModelBinder.Bind(viewModel, element, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }

            if (element is ContentView view)
            {
                page = CreateContentPage(view, viewModel);
            }
            return(_navigationPage.PushAsync(page, animated));
        }
Esempio n. 30
0
        public override void Dispatch(IViewContext viewContext, IEnumerable <DomainEvent> batch, IViewManagerProfiler viewManagerProfiler)
        {
            var updatedViews = new HashSet <TViewInstance>();
            var eventList    = batch.ToList();

            if (BatchDispatchEnabled)
            {
                var domainEventBatch = new DomainEventBatch(eventList);
                eventList.Clear();
                eventList.Add(domainEventBatch);
            }

            foreach (var e in eventList)
            {
                if (ViewLocator.IsRelevant <TViewInstance>(e))
                {
                    var stopwatch       = Stopwatch.StartNew();
                    var affectedViewIds = _viewLocator.GetAffectedViewIds(viewContext, e);

                    foreach (var viewId in affectedViewIds)
                    {
                        var viewInstance = _views.GetOrAdd(viewId, id => _dispatcher.CreateNewInstance(id));

                        _dispatcher.DispatchToView(viewContext, e, viewInstance);

                        updatedViews.Add(viewInstance);
                    }

                    viewManagerProfiler.RegisterTimeSpent(this, e, stopwatch.Elapsed);
                }

                Interlocked.Exchange(ref _position, e.GetGlobalSequenceNumber());
            }

            RaiseUpdatedEventFor(updatedViews);
        }
Esempio n. 31
0
        public void Should_not_resolve_user_control()
        {
            DISetup.SetupContainer();
            var resolver = new Mock <IViewResolver>();

            resolver.Setup(p => p.FormatUserControlName(It.IsAny <object>())).Returns(string.Empty);
            resolver.Setup(p => p.IsControl(It.IsAny <string>())).Returns(true);
            resolver.Setup(p => p.ResolveUserControl(It.IsAny <object>())).Returns(() =>
            {
                throw new Exception("Fake");
            });
            DISetup.Container.RegisterInstance(resolver.Object);
            var logger = new Mock <ILogger>();

            logger.Setup(p => p.Info(It.IsAny <string>()));
            logger.Setup(p => p.Error(It.IsAny <Exception>(), It.IsAny <string>()));
            DISetup.Container.RegisterInstance(logger.Object);

            var locator = new ViewLocator();
            var result  = locator.Build(new FakeVM());

            result.GetType().Should().Be(typeof(TextBlock));
            ((TextBlock)result).Text.Should().Contain("Not Found");
        }
Esempio n. 32
0
        /// <summary>
        /// Shows a popup at the current mouse position.
        /// </summary>
        /// <param name="rootModel">The root model.</param>
        /// <param name="context">The view context.</param>
        /// <param name="settings">The optional popup settings.</param>
        public virtual async Task ShowPopupAsync(object rootModel, object context = null, IDictionary <string, object> settings = null)
        {
            var popup = this.CreatePopup(rootModel, settings);
            var view  = ViewLocator.LocateForModel(rootModel, popup, context);

            popup.Child = view;
            popup.SetValue(View.IsGeneratedProperty, true);

            ViewModelBinder.Bind(rootModel, popup, null);
            Caliburn.Micro.Action.SetTargetWithoutContext(view, rootModel);

            if (rootModel is IActivate activator)
            {
                await activator.ActivateAsync();
            }

            if (rootModel is IDeactivate deactivator)
            {
                popup.Closed += async(s, e) => await deactivator.DeactivateAsync(true);
            }

            popup.IsOpen = true;
            popup.CaptureMouse();
        }
Esempio n. 33
0
        protected override void Configure()
        {
            TypeMappingConfiguration map = new TypeMappingConfiguration()
            {
                DefaultSubNamespaceForViewModels = "Scrubbler.ViewModels",
                DefaultSubNamespaceForViews      = "Scrubbler.Views"
            };

            ViewLocator.ConfigureTypeMappings(map);
            ViewLocator.AddSubNamespaceMapping("Scrubbler.ViewModels.ScrobbleViewModels", "Scrubbler.Views.ScrobbleViews");
            ViewLocator.AddSubNamespaceMapping("Scrubbler.ViewModels.SubViewModels", "Scrubbler.Views.SubViews");
            ViewModelLocator.ConfigureTypeMappings(map);

            _container = new SimpleContainer();
            _container.Singleton <IWindowManager, WindowManager>();
            _container.Singleton <IExtendedWindowManager, ExtendedWindowManager>();
            _container.Singleton <ILastFMClientFactory, LastFMClientFactory>();
            _container.Singleton <IScrobblerFactory, ScrobblerFactory>();
            _container.Singleton <ILocalFileFactory, LocalFileFactory>();
            _container.Singleton <IFileOperator, FileOperator>();
            _container.Singleton <IDirectoryOperator, DirectoryOperator>();
            _container.Singleton <ISerializer <User>, DCSerializer <User> >();
            _container.PerRequest <MainViewModel>();
        }
Esempio n. 34
0
        /// <summary>
        /// Configure the container.
        /// </summary>
        protected override void Configure()
        {
            base.Configure();

            if (!Execute.InDesignMode)
            {
                KernelConfigurator.Configure(_kernel, _catalog.Modules);

#pragma warning disable S2696
                LogManager.GetLog = type => _kernel.Get <IUILogService>(new ConstructorArgument("type", type));
#pragma warning restore S2696
            }

            ViewLocator.AddNamespaceMapping("*", "Logikfabrik.Overseer.WPF.Client.Views");

            _catalog = null;

            LanguageConfigurator.Configure(_kernel.Get <IAppSettingsFactory>());
            DataBindingLanguageConfigurator.Configure();
            DataBindingActionConfigurator.Configure();
            ConventionConfigurator.Configure();
            ErrorLogHandlerConfigurator.Configure(_kernel.Get <AppDomain>(), _kernel.Get <IApp>(), _kernel.Get <ILogService>());
            BuildNotificationConfigurator.Configure(_kernel.Get <IBuildTracker>(), _kernel.Get <IBuildNotificationManager>());
        }
Esempio n. 35
0
            public void ThrowsArgumentNullExceptionForNullTypeToResolve()
            {
                var viewLocator = new ViewLocator();

                ExceptionTester.CallMethodAndExpectException <ArgumentNullException>(() => viewLocator.IsCompatible(null, typeof(FollowingNoNamingConventionView)));
            }
Esempio n. 36
0
            public void ThrowsArgumentNullExceptionForNullViewType()
            {
                var viewLocator = new ViewLocator();

                ExceptionTester.CallMethodAndExpectException <ArgumentNullException>(() => viewLocator.ResolveView(null));
            }
Esempio n. 37
0
 public void Recording(object arg)
 {
     NavigationService.Navigate(ViewLocator.View("RecordingSettings"));
 }
            public void ShouldThrowOnEmptyFileName()
            {
                var fileSystem = new Mock<IFileSystem>();
                fileSystem.SetupGet(x => x.CurrentDirectory).Returns("C:\\");
                fileSystem.Setup(x => x.FileExists(It.IsAny<string>())).Returns(false);

                var viewLocator = new ViewLocator(fileSystem.Object);

                var exception = Assert.Throws<ArgumentNullException>(() => viewLocator.LocateViewFor(string.Empty));

                exception.Message.ShouldContain("Parameter name: viewModelName");
            }
Esempio n. 39
0
 public UIMethods(ViewLocator viewLocator)
 {
     _viewLocator = viewLocator;
 }
            public void ShouldThrowIfFileDoesntExist()
            {
                var fileSystem = new Mock<IFileSystem>();
                fileSystem.SetupGet(x => x.CurrentDirectory).Returns("C:\\");
                fileSystem.Setup(x => x.FileExists(It.IsAny<string>())).Returns(false);

                var viewLocator = new ViewLocator(fileSystem.Object);

                var exception = Assert.Throws<InvalidOperationException>(() => viewLocator.LocateViewFor("TestViewModel"));

                exception.Message.ShouldContain("Tried: C:\\TestView.xaml");
            }
 public SearchViewModel(ViewLocator locator, SharedModel sharedModel)
 {
     _locator = locator;
     _sharedModel = sharedModel;
 }
 public DetailsViewModel(ViewLocator locator, SharedModel sharedModel)
 {
     _locator = locator;
     _sharedModel = sharedModel;
 }
            public void ShouldThrowIfTypeNameDoesntEndWithViewModel()
            {
                var fileSystem = new Mock<IFileSystem>();
                var viewLocator = new ViewLocator(fileSystem.Object);

                var exception = Assert.Throws<InvalidOperationException>(() => viewLocator.LocateViewFor("SomeClass"));

                exception.Message.ShouldContain("The ViewModel type name has to end with 'ViewModel'");
            }
Esempio n. 44
0
            public void ThrowsArgumentNullExceptionForNullResolvedType()
            {
                var viewLocator = new ViewLocator();

                ExceptionTester.CallMethodAndExpectException <ArgumentNullException>(() => viewLocator.IsCompatible(typeof(NoNamingConventionViewModel), null));
            }
 public SuccessViewModel(ViewLocator locator, SharedModel sharedModel, IKernel kernel)
 {
     _locator = locator;
     _sharedModel = sharedModel;
     _kernel = kernel;
 }