public MainWindowViewModel() { CurrentDispatcher = Dispatcher.CurrentDispatcher; #region Commands initialization checkDevicesGroupCommand = new SimpleCommand { ExecuteDelegate = CheckDevicesGroup }; checkDeviceCommand = new SimpleCommand { ExecuteDelegate = CheckDevice }; installCommand = new SimpleCommand { ExecuteDelegate = x => Install() }; cancelInstallCommand = new SimpleCommand { ExecuteDelegate = x => CancelInstall() }; closeCommand = new SimpleCommand { ExecuteDelegate = x => Close() }; #endregion }
public void CanVerifyWhenIsBoundToInstanceMethodsOnAnotherObject() { var other = new SimpleCommandExposesItsBindingsForTestVerification(); _testSubject = new SimpleCommand(other._CorrectCanExecuteInstanceMethod, other._CorrectExecuteInstanceMethod); Assert.That(_testSubject.MethodHandlingCanExecute, Calls.To(() => other._CorrectCanExecuteInstanceMethod())); Assert.That(_testSubject.MethodHandlingExecute, Calls.To(() => other._CorrectExecuteInstanceMethod())); }
public MultiSelectionViewModel() { MarkSelectedAsDownloadedCommand = new SimpleCommand<object,object>(delegate { foreach (var episode in SelectedEpisodes) { episode.Downloaded = true; } OnPropertyChanged("InfoText2"); }); MarkSelectedAsWatchedCommand = new SimpleCommand<object, object>(delegate { foreach (var episode in SelectedEpisodes) { episode.Watched = true; episode.Downloaded = true; } OnPropertyChanged("InfoText2"); }); UnmarkSelectedCommand= new SimpleCommand<object, object>(delegate { foreach (var episode in SelectedEpisodes) { episode.Watched = false; episode.Downloaded = false; } OnPropertyChanged("InfoText2"); }); }
public void AssertionFiresWhenBindingIsNotAsExpected() { var other = new SimpleCommandExposesItsBindingsForTestVerification(); _testSubject = new SimpleCommand(_CorrectCanExecuteInstanceMethod, other._CorrectExecuteInstanceMethod); var actualBinding = Extract.BindingInfoFrom(() => other._CorrectExecuteInstanceMethod()).ToString(); _AssertionShouldFail(() => _CorrectExecuteStaticMethod(), "bound to incorrect method", actualBinding); _AssertionShouldFail(() => _CorrectExecuteInstanceMethod(), "bound to incorrect object instance", actualBinding); }
public RibbonViewModel() : base("FutureModule Ribbon", true, false) { StaticViewName = "FutureModule Ribbon"; GetDataCommand = new SimpleCommand<object>(o => _canGetData, GetData); OpenModuleCommand = new SimpleCommand<bool>(OpenModule); OpenButtonContent = "Open Future Module"; }
public void CanExecute_WhenACanExecuteDelegateIsPassedThatEvaluatesToFalse_CanExecuteShouldReturnFalse() { var command = new SimpleCommand(() => { }, () => false); var result = command.CanExecute(); Assert.IsFalse(result, "CanExecute should return false as there is a delegate and it returns false"); }
public void CanExecute_WhenNoCanExecuteDelegateIsPassed_CanExecuteShouldReturnTrue() { var command = new SimpleCommand(() => { }); var result = command.CanExecute(); Assert.IsTrue(result,"CanExecute should always return true when no delgate is given."); }
public TileViewModelBase( IRegionManager regionManager, IMessageBoxService messageBoxService) { this.regionManager = regionManager; this.messageBoxService = messageBoxService; CloseViewCommand = new SimpleCommand<object, object>(ExecuteCloseViewCommand); }
public TaskListsViewModel() { TaskLists = new ObservableCollection<TaskList>(); SyncWithGoogleCommand = new SimpleCommand(SyncWithGoogle, CanSyncWithGoogle); DisplayTasksForTaskListCommand = new SimpleCommand(DisplayTasksForTaskList, IsTaskListSelected); RefreshTaskLists(); IsLoading = false; }
//注册 public void RegisterMultiCommand(SimpleCommand commandClassRef, params string[] notificationName) { int count = notificationName.Length; for (int i = 0; i < count; i++) { RegisterCommand(notificationName[i], commandClassRef.GetType()); } }
public TasksViewModel(int taskListId) { EditTaskCommand = new SimpleCommand(EditTask, CanEditTask); NewTaskCommand = new SimpleCommand(NewTask); Tasks = new ObservableCollection<Task>(); TaskContainer.GetTasksForTaskList(taskListId).ForEach(p => Tasks.Add(p)); _taskList = TaskContainer.GetTaskList(taskListId); }
public EpisodeViewModel(FavEpisodeData favEpisodeData) { _favEpisodeData = favEpisodeData; Photo = (_favEpisodeData.EpisodeInformation == null || String.IsNullOrWhiteSpace(_favEpisodeData.EpisodeInformation.Image)) ? null : new CachedBitmap(_favEpisodeData.EpisodeInformation.Image); NewEpisodeVisible = (_favEpisodeData.NewEpisode) ? Visibility.Visible : Visibility.Collapsed; NewUpdateVisible = (_favEpisodeData.NewUpdate) ? Visibility.Visible : Visibility.Collapsed; DownloadedCheckVisibility = (_favEpisodeData.Downloaded) ? Visibility.Visible : Visibility.Collapsed; WatchedCheckVisibility = (_favEpisodeData.Watched) ? Visibility.Visible : Visibility.Collapsed; _dispatcher = Dispatcher.CurrentDispatcher; favEpisodeData.PropertyChanged += favEpisodeData_PropertyChanged; ShowInfoCommand = new SimpleCommand<object, object>(b => (_favEpisodeData.EpisodeInformation != null && (!String.IsNullOrWhiteSpace(_favEpisodeData.EpisodeInformation.ProviderHomepage)||!String.IsNullOrWhiteSpace( _favEpisodeData.EpisodeInformation.PublisherHomepage))), delegate { var p = new Process(); p.StartInfo.FileName = favEpisodeData.EpisodeInformation.PublisherHomepage != null ? _favEpisodeData.EpisodeInformation.PublisherHomepage : _favEpisodeData.EpisodeInformation.ProviderHomepage; p.Start(); }); StateChangeCommand = new SimpleCommand<object, object>(o => { if (!_favEpisodeData.Downloaded && !_favEpisodeData.Watched) { _favEpisodeData.Downloaded = true; return; } if (_favEpisodeData.Downloaded && !_favEpisodeData.Watched) { _favEpisodeData.Watched = true; return; } _favEpisodeData.Downloaded = false; _favEpisodeData.Watched = false; }); DownloadCommand = new SimpleCommand<object, String>(s => { _favEpisodeData.Downloaded = true; for (int i = 0; i < 10; i++) { try { Clipboard.SetText(s); Clipboard.Flush(); Stats.TrackAction(Stats.TrackActivity.Download); return; } catch { //nah } Thread.Sleep(10); } MessageBox.Show("Couldn't Copy link to clipboard.\n" + s); }); }
public FitPanel() { Channel0PeakFinderSetting = new PeakFinderSetting() { Channel = 0 }; Channel1PeakFinderSetting = new PeakFinderSetting() { Channel = 1 }; DebugPrint = new SimpleCommand<object>(o => Debug.WriteLine(o)); UsePeakGuessForChannel0Command = new SimpleCommand<InitialPeakGuess>(o => UsePeakGuess(o, 0)); UsePeakGuessForChannel1Command = new SimpleCommand<InitialPeakGuess>(o => UsePeakGuess(o, 1)); InitializeComponent(); }
public RibbonViewModel() : base("BondModule Ribbon", true, false) { StaticViewName = "BondModule Ribbon"; GetDataCommand = new SimpleCommand<object>(o => _canGetData, GetData); OpenModuleCommand = new SimpleCommand<bool>(OpenModule); PauseCommand = new SimpleCommand<object>(o => _canGetData, _ => Mediator.GetInstance.Broadcast(Topic.BondModuleHang)); OpenButtonContent = "Open Bond Module"; }
public FutureViewModel() : base("Future Module", true, true) { DynamicViewName = "Future Module"; //Mediator.GetInstance.RegisterInterest<Entity>(Topic.MockBondServiceDataReceived, DataReceived); //var grid = GetRef<DataGrid>("MainGrid"); Entities = new NotifyCollection<Entity>(EntityBuilder.LoadMetadata(AssetType.Common, AssetType.Future)); CreateColumnsCommand = new SimpleCommand<Object, EventToCommandArgs>((parameter) => true, CreateColumns); }
public void ICommandExecute_CallsTheGivenDelegate_TheGivenDelegateIsCalled() { var called = false; var command = new SimpleCommand(() => { called = true; }); ((ICommand)command).Execute(null); Assert.IsTrue(called); }
public ExportViewmodel(MediaManager mediaManager, IEnumerable<MediaExport> exportList) { Items = new ObservableCollection<MediaExportViewmodel>(exportList.Select(m => new MediaExportViewmodel(m))); Directories = mediaManager.IngestDirectories.Where(d => d.IsXDCAM).ToList(); SelectedDirectory = Directories.FirstOrDefault(); CommandExport = new SimpleCommand() { ExecuteDelegate = _export, CanExecuteDelegate = _canExport }; _mediaManager = mediaManager; this._view = new Views.ExportView() { DataContext = this, Owner = System.Windows.Application.Current.MainWindow, ShowInTaskbar=false }; _view.ShowDialog(); }
/// <summary> /// Adds a new button to the Intelligence Portal header. /// </summary> /// <param name="headerButtonCaption">The caption to display in the button.</param> /// <param name="headerButtonTooltip">The test to display in the tooltip when a user hivers the mouse over the button.</param> /// <param name="buttonCommand">The command to run when the button is clicked.</param> public void RegisterHeaderCommand( string headerButtonCaption, string headerButtonTooltip, SimpleCommand buttonCommand) { // Unfortunately we may well be called before the header bar is actually on screen, so // we need to loop until it's there (or the initialization code times us out) var timer = mContainer.Resolve<IDispatcherTimer>(); timer.Interval = TimeSpan.FromMilliseconds(10); timer.Tick += delegate { var toolboxView = Application.Current.RootVisual.GetVisualDescendants().OfType<ToolboxView>().SingleOrDefault(); if (toolboxView == null) { // Toolbox not visible yet. return; } // Toolbox is visible now. timer.Stop(); // Find the grid that contains the buttons var layoutGrid = (Grid)toolboxView.Content; var grid2 = (Grid)layoutGrid.Children[0]; var grid3 = (Grid)grid2.Children[0]; var grid4 = (Grid)grid3.Children[0]; var destinationGrid = grid4; // Add a new column definition var existingColCount = destinationGrid.ColumnDefinitions.Count; destinationGrid.ColumnDefinitions.Add(new ColumnDefinition()); // Add the button. var button = new HeaderButton(); button.HeaderButtonTextBlockBase.Text = headerButtonCaption; button.HeaderButtonTextBlockHighlight.Text = headerButtonCaption; var tooltip = ToolTipService.GetToolTip(button.ButtonControl) as ToolTip; if(tooltip != null) { tooltip.Content = headerButtonTooltip; } button.ButtonControl.Command = buttonCommand; button.SetValue(Grid.ColumnProperty, existingColCount); destinationGrid.Children.Add(button); }; timer.Start(); }
public BondViewModel() : base("Bond Module", true, true) { DynamicViewName = "Bond Module"; _grid = GetRef<DataGrid>("MainGrid"); // InputManager.Current.PreProcessInput += new PreProcessInputEventHandler(Current_PreProcessInput); // InputManager.Current.PostProcessInput += new ProcessInputEventHandler(Current_PostProcessInput); Entities = new NotifyCollection<Entity>(EntityBuilder.LoadMetadata(AssetType.Common, AssetType.Bond)); CreateColumnsCommand = new SimpleCommand<Object, EventToCommandArgs>((parameter) => true, CreateColumns); }
public ShellViewModel(IEventMessager eventMessager) { Title = "Big XAML Apps Demo"; ShowSpotTileCommand = new SimpleCommand<object, object>(x => eventMessager.Publish(new ShowNewSpotTileMessage())); SpotTrades = new ObservableCollection<SpotTrade>(); eventMessager.Observe<SpotTrade>() .Subscribe(x => { this.SpotTrades.Add(x); base.RaisePropertyChanged(()=>SpotTrades); }); }
private void SetCommands() { Action <object> playMusicFromList = PlayMusicFromList; Func <Task> playListGettingCommand = GetPlayList; Action playOnButton = PlayOnButton; Action playForward = PlayForward; Action playBackword = PlayBackward; PlayFromList = new CommandWithParammeter(playMusicFromList); FolderLoadCommand = new AsyncCommand(playListGettingCommand); PlayOnButtonCommand = new SimpleCommand(playOnButton); PlayForwardCommand = new SimpleCommand(playForward); PlayBackwardCommand = new SimpleCommand(playBackword); }
public JobTasksViewModel( MainWindowViewModel parent, JobsListViewModel jobsListViewModel, JobsRunsGetViewModel jobsRunsGetViewModel, JobsRunNowViewModel jobsRunNowViewModel, JobsPickAndRunJarViewModel jobsPickAndRunJarViewModel ) { JobsListViewModel = jobsListViewModel; JobsRunsGetViewModel = jobsRunsGetViewModel; JobsRunNowViewModel = jobsRunNowViewModel; JobsPickAndRunJarViewModel = jobsPickAndRunJarViewModel; GoBackCommand = new SimpleCommand <object, object>(x => parent.CurrentTaskViewModel = parent); }
public AddUpdateViewModel(IUserAPI api, UserModel userModel = null) { userApi = api; model = userModel; IsSaveSuccessful = false; operationType = userModel == null ? Operations.CreateNewUser : Operations.UpdateUser; WindowCaption = userModel == null ? "Add New User" : "Update User"; SaveButtonCaption = userModel == null ? "Add" : "Update"; SaveCommand = new SimpleCommand(OnSave, CanSave); if (userModel != null) { SetUserModel(userModel); } }
public void FindsNull_GivenThreeMisspellings() { var command = new SimpleCommand("Hello", ""); var list = new CommandList( new List <IBotCommand> { command, }, 2); var match = list.FindCommandByKeyword("Halku", out _); match.Should().Be(null); }
public void FindsMatch_GivenThreeMisspellings_AndMaxDistanceSetToThree() { var command = new SimpleCommand("Hello", ""); var list = new CommandList( new List <IBotCommand> { command, }, 3); var match = list.FindCommandByKeyword("Halku", out _); match.Should().Be(match); }
public WorkViewModel(Orders orders) { _orders = orders; Delete = new SimpleCommand(id => { SQL.Delete(SQL.GetWork().First(w => w.Id == (int)id)); SQL.AddHistory(_orders.IdOrder, String.Format("Удаление работы: {0}", WorkName)); Load(); }); Edit = new SimpleCommand(id => { var a = ShowWin.AddedWork(SQL.GetWork().First(w => w.Id == (int)id)); a.OnClose += Load; }); AddWork = new SimpleCommand(() => { if (!SQL.GetDicWork().Contains(WorkName)) { SQL.Add(new DicWork() { Work = WorkName, Price = Price }); } SQL.Add(new Works() { IdOrder = _orders.IdOrder, IdWork = SQL.GetIdWork(WorkName), Count = Count == 0 ? 1 : Count, Price = Price }); SQL.AddHistory(_orders.IdOrder, String.Format("Добавлена работа: {0}", WorkName)); Load(); }); Load(); DicWorkEntries.CurrentChanged += (u, e) => { if (DicWorkEntries.CurrentItem != null) { Price = SQL.GetAllDicWork() .First(w => w.IdWork == SQL.GetIdWork(DicWorkEntries.CurrentItem.ToString())) .Price; } }; }
public SettingsViewModel(Core.Settings settings) { Settings = settings; List <string> temp = new List <string> { "View", "Split", "Edit" }; NoteViewModes = temp; ChangeThemeCommand = new RelayCommand(ChangeTheme); SaveSettingsCommand = new RelayCommand(SaveSettings); BackupNowCommand = new RelayCommand(Backup); TurnOnEncryptionCommand = new SimpleCommand(TurnOnEncryption); TurnOffEncryptionCommand = new SimpleCommand(TurnOffEncryption); SecureNotesEnabled = Hub.Instance.EncryptionManager.SecureNotesEnabled; InitBackupLabel(); //Themes = new List<string> {"Dark", "Light"}; //AccentColors = ThemeManager.Accents // .Select(a => new AccentColorMenuData() { Name = a.Name, ColorBrush = a.Resources["AccentColorBrush"] as Brush }) // .ToList(); AccentColors = new List <AccentColorMenuData> { new AccentColorMenuData { AccentName = "VSDark", Name = "Dark" }, new AccentColorMenuData { AccentName = "VSLight", Name = "Light" } }; // create metro theme color menu items for the demo //AppThemes = ThemeManager.AppThemes // .Where(a => a.Name == "VSDark") // .Select(a => new AppThemeMenuData() { Name = a.Name, BorderColorBrush = a.Resources["BlackColorBrush"] as Brush, ColorBrush = a.Resources["WhiteColorBrush"] as Brush }) // .ToList(); // AppThemes = ThemeManager.AppThemes.Select(a => new AppThemeMenuData() { Name = a.Name, BorderColorBrush = a.Resources["BlackColorBrush"] as Brush, ColorBrush = a.Resources["WhiteColorBrush"] as Brush }) // .ToList(); // AccentColors = ThemeManager.Accents.Select(a => new AccentColorMenuData() { Name = a.Name, ColorBrush = a.Resources["AccentColorBrush"] as Brush }) // .ToList(); SelectedAccent = AccentColors.FirstOrDefault(a => a.Name == Settings.Accent); //SelectedTheme = AppThemes.FirstOrDefault(a => a.Name == Settings.Theme); }
public void WhenExecutedFilterVaryByParamsSetIncorrectlyThenCacheIsAlwaysUsed() { // Arrange CacheAttribute filter = this.CreateAttribute(new MemoryCache("test")); filter.Duration = 10; filter.VaryByParams = "XXXX"; CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); SimpleCommand command1 = new SimpleCommand { Property1 = 1, Property2 = "test1" }; CommandHandlerRequest request1 = new CommandHandlerRequest(this.config, command1); CommandHandlerContext context1 = new CommandHandlerContext(request1, descriptor); CommandHandlerExecutedContext executedContext1 = new CommandHandlerExecutedContext(context1, null); executedContext1.SetResponse("result1"); SimpleCommand command2 = new SimpleCommand { Property1 = 2, Property2 = "test2" }; CommandHandlerRequest request2 = new CommandHandlerRequest(this.config, command2); CommandHandlerContext context2 = new CommandHandlerContext(request2, descriptor); CommandHandlerExecutedContext executedContext2 = new CommandHandlerExecutedContext(context2, null); executedContext2.SetResponse("result2"); SimpleCommand command3 = new SimpleCommand { Property1 = 2, Property2 = "test3" }; CommandHandlerRequest request3 = new CommandHandlerRequest(this.config, command3); CommandHandlerContext context3 = new CommandHandlerContext(request3, descriptor); CommandHandlerExecutedContext executedContext3 = new CommandHandlerExecutedContext(context3, null); executedContext3.SetResponse("result3"); // Act filter.OnCommandExecuting(context1); filter.OnCommandExecuted(executedContext1); filter.OnCommandExecuting(context2); filter.OnCommandExecuted(executedContext2); filter.OnCommandExecuting(context3); filter.OnCommandExecuted(executedContext3); // Assert Assert.Equal("result1", executedContext1.Response.Value); Assert.Equal("result1", executedContext2.Response.Value); Assert.Equal("result1", executedContext3.Response.Value); }
public ViewAllUsersViewViewModel(IMessageBoxService messageBoxService, IViewAwareStatus viewAwareStatus, IViewInjectionService viewInjectionService, IUserService userService, IOpenFileService openFileService) { this.messageBoxService = messageBoxService; this.viewAwareStatus = viewAwareStatus; this.userService = userService; this.viewInjectionService = viewInjectionService; this.openFileService = openFileService; Mediator.Instance.Register(this); //Initialise Commands UpdateUserCommand = new SimpleCommand <object, object>(CanExecuteUpdateUserCommand, ExecuteUpdateUserCommand); UploadUserImageCommand = new SimpleCommand <object, object>(CanExecuteUploadUserImageCommand, ExecuteUploadUserImageCommand); viewAwareStatus.ViewLoaded += new Action(viewAwareStatus_ViewLoaded); }
public BuildProjectViewModel(IObserver <ProjectBuildpathRequest> updatePath, string?path, string project, LocLocalizer localizer, IDialogFactory dialogFactory, string?source) { _path = path ?? string.Empty; Project = project; _localizer = localizer; _dialogFactory = dialogFactory; source = source?.GetDirectoryName(); _source = string.IsNullOrWhiteSpace(source) ? Environment.CurrentDirectory : source; _updatePath = updatePath; Label = string.Format(localizer.MainWindowBuildProjectLabel, project); Search = new SimpleCommand(SetPathDialog); }
static void Main() { // The client code can parameterize an invoker with any commands. Invoker invoker = new Invoker(); SimpleCommand simpleCommand = new SimpleCommand(message: "Hello, World!"); invoker.SetOnStart(simpleCommand); ComplexCommand complexCommand = new ComplexCommand(receiver: new Receiver(), work1: "Send email", work2: "Save report"); invoker.SetOnFinish(complexCommand); invoker.DoSomethingImportant(); }
public CreateOrderDialogViewModel( IMessageBoxService messageBoxService, Guid orderId, IEnumerable<StoreItemViewModel> items) : base("Create Order") { this.messageBoxService = messageBoxService; this.OrderItems = items.Select(x => new OrderItem() { OrderId = orderId, StoreItemId = x.Id, StoreItemDescription = x.Description, StoreItemUrl = x.ImageUrl }); OkCommand = new SimpleCommand<object, object>(x => Validate()); }
public TriggersViewModel(IUIVisualizerService uiVisualizer, IMessageBoxService messageBoxService, IViewAwareStatus viewAwareStatusService) { this.uiVisualizer = uiVisualizer; this.messageBoxService = messageBoxService; this.viewAwareStatusService = viewAwareStatusService; this.viewAwareStatusService.ViewLoaded += ViewAwareStatusService_ViewLoaded; _backgroundWorker = new BackgroundWorker(); _backgroundWorker.DoWork += _backgroundWorker_DoWork; _backgroundWorker.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted; //Commands DoCopyToClipboardCommand = new SimpleCommand <Object, Object>(ExecuteDoCopyToClipboardCommand); DoSaveAsCommand = new SimpleCommand <Object, Object>(ExecuteDoSaveAsCommand); }
/// <summary> /// Initializes a new instance of the <see cref="ExpandableRegionViewModel"/> class. /// </summary> public ExpandableRegionViewModel( IProvider <IIntentManager> intentManagerProvider, IExpandableRegionView view) { // Create the command that the inserted // expandable region button will use. mLaunchSubsettingTabCommand = new SimpleCommand { Action = LaunchSubsettingTab }; mIntentManagerProvider = intentManagerProvider; SetAsViewModelForView(view); }
private void setupDoWorkCommand() { DoWorkCommand = new SimpleCommand { CanExecuteDelegate = x => { return(EmbeddedModel.CanDoWork && EmbeddedModel.NotificationMode != NotificationMode.Processing); }, ExecuteDelegate = x => { EmbeddedModel.DoWork(); } }; }
public IdleModel() : base() { icons.Add("lexianggame"); icons.Add("haidilao"); icons.Add("kendeji"); this.showWheelRequest = new InteractionRequest <WheelViewModel>(this); this.showWheel = new SimpleCommand(() => { var model = new WheelViewModel(); showWheelRequest.Raise(model); }); Icon = icons[0]; }
public CreateOrderDialogViewModel( IMessageBoxService messageBoxService, Guid orderId, IEnumerable <StoreItemViewModel> items) : base("Create Order") { this.messageBoxService = messageBoxService; this.OrderItems = items.Select(x => new OrderItem() { OrderId = orderId, StoreItemId = x.Id, StoreItemDescription = x.Description, StoreItemUrl = x.ImageUrl }); OkCommand = new SimpleCommand <object, object>(x => Validate()); }
public MainViewModel(IMessageBoxService service) { this.service = service; MiListilla = new List <string> { "Hello", "I enjoy a lot", "doing Drag", "and", "Drop!", "Oh yeah!", }; ShowMessageCommand = new SimpleCommand <object, object>(o => service.ShowInformation(string.Format("You've dropped a {0} into a {1}", o.ToString(), DropTarget))); }
/// <summary> /// Constructor /// </summary> /// <param name="dispatcher">The dispatcher of the View</param> public DevelopersViewModel(Dispatcher dispatcher) { this.dispatcher = dispatcher; Developers = new ObservableCollection <WPFDisciples.Backend.Developers>(); //Register to the Mediator.Register(x => LoadData(), ViewModelMessages.ShowDevelopers); //Create the SelectDeveloper handlers SelectDeveloper = new SimpleCommand { //Notify subscibers that a developer has been selected and pass on the selected developer as parameter ExecuteDelegate = x => Mediator.NotifyColleagues(ViewModelMessages.SelectDeveloper, SelectedDeveloper) }; }
public RibbonViewModel(IApplicationServices applicationServices, ICommonServices commonServices) { _applicationServices = applicationServices; _commonServices = commonServices; _dispatcher = Dispatcher.CurrentDispatcher; _applicationServices.HartCommunicationService.PropertyChanged += HartCommunicationServiceOnPropertyChanged; PortState = _applicationServices.HartCommunicationService.PortState; ConnectionCommand = new AsyncCommand <object, object>(OnConnect, arg => !IsConnectionChanging()); ConfigurateConnectionCommand = new SimpleCommand <object, object>(item => PortState == PortState.Closed, OnConfigurationConnection); CreateSendCommands(); }
private void setupCommands() { ContextMenuCommand = new SimpleCommand() { CanExecuteDelegate = (x) => { return(SelectedNavigationViewModel != null && SelectedNavigationViewModel.ContextMenuCommand.CanExecute(x)); }, ExecuteDelegate = (x) => { SelectedNavigationViewModel.ContextMenuCommand.Execute(x); } }; }
public void SimpleCommandWithArgsTest() { ShellParser shellParser = MakeParser("git reset --hard"); SimpleCommandContext context = shellParser.simpleCommand(); ShellVisitor visitor = new ShellVisitor(); ParserResult result = visitor.Visit(context); SimpleCommand actualCommand = result.SimpleCommandValue; result.IsSimpleCommand.Should().BeTrue(); actualCommand.Command.Should().Be("git"); actualCommand.Arguments.Should().BeEquivalentTo(new List <string> { "reset", "--hard" }, opt => opt.WithStrictOrdering()); }
public ViewModel() { Animation = new Animation(this); InteriorModel = new InteriorModel(); lineAndEllipse = new LineAndEllipseAnimation(InteriorModel, this); PublicModel = new MainModel(InteriorModel, Animation, this); #region Requests RequestRotateFrequency = new SimpleCommand <double>(RotateFrequencyTo); RequestEndRotateFrequency = new SimpleCommand <double>(EndRotateFrequencyTo); RequestRotateNoise = new SimpleCommand <double>(RotateNoiseTo); RequestEndRotateNoise = new SimpleCommand <double>(EndRotateNoiseTo); RequestRotateVolume = new SimpleCommand <double>(RotateVolumeTo); RequestEndRotateVolume = new SimpleCommand <double>(EndRotateVolumeTo); RequestRotateAntenna = new SimpleCommand <double>(RotateAntennaTo); RequestEndRotateAntenna = new SimpleCommand <double>(EndRotateAntennaTo); RequestRotateAntennaFixer = new SimpleCommand <double>(RotateAntennaFixerTo); RequestEndRotateAntennaFixer = new SimpleCommand <double>(EndRotateAntennaFixerTo); RequestRotateRange = new SimpleCommand <double>(RotateRangeTo); RequestRotateVoltage = new SimpleCommand <double>(RotateVoltageTo); RequestRotateWorkMode = new SimpleCommand <double>(RotateWorkModeTo); RequestChangePowerValue = new SimpleCommand <bool>(ChangePowerValueTo); RequestChangeScaleValue = new SimpleCommand <bool>(ChangeScaleValueTo); RequestChangeToneValue = new SimpleCommand <bool>(ChangeToneValueTo); RequestChangeTangentValue = new SimpleCommand <bool>(ChangeTangentValueTo); RequestChangeSubFrequency0Value = new SimpleCommand <bool>(ChangeSubFrequency0ValueTo); RequestChangeSubFrequency1Value = new SimpleCommand <bool>(ChangeSubFrequency1ValueTo); RequestChangeSubFrequency2Value = new SimpleCommand <bool>(ChangeSubFrequency2ValueTo); RequestChangeSubFrequency3Value = new SimpleCommand <bool>(ChangeSubFrequency3ValueTo); RequestRotateClamp0 = new SimpleCommand <double>(ChangeClamp0AngleTo); RequestRotateClamp1 = new SimpleCommand <double>(ChangeClamp1AngleTo); RequestRotateClamp2 = new SimpleCommand <double>(ChangeClamp2AngleTo); RequestRotateClamp3 = new SimpleCommand <double>(ChangeClamp3AngleTo); #endregion AntennaFixerAngle = Converter.AntennaFixer.ToAngle(ClampState.Fixed); VisibilityFrequencyDisplay = Visibility.Hidden; Clamp0Angle = 90; Clamp1Angle = 90; Clamp2Angle = 90; Clamp3Angle = 90; UpdateCanChangeFrequency(); }
public async Task ExecutesCancellableHandlerWithResult() { // Arrange CommandHandlerExecuter testSubject = new CommandHandlerExecuter(); CancellableSimpleCommandHandler handler = new CancellableSimpleCommandHandler(); SimpleCommand command = new SimpleCommand(); testSubject.CompileHandlerExecuter(typeof(SimpleCommand), typeof(CancellableSimpleCommandHandler)); // Act SimpleResult result = await testSubject.ExecuteAsync(handler, command, null, CancellationToken.None); // Assert Assert.Single(result.Handlers); Assert.Equal(typeof(CancellableSimpleCommandHandler), result.Handlers.Single()); }
/// <summary> /// Initializes a new instance of the <see cref="GameViewModel"/> class. /// </summary> /// <param name="gameService">The game service.</param> /// <param name="uiDispatcher">The UI dispatcher.</param> /// <exception cref="ArgumentNullException"> /// gameService /// or /// uiDispatcher /// </exception> public GameViewModel(GameService gameService, Dispatcher uiDispatcher) { _gameService = gameService ?? throw new ArgumentNullException(nameof(gameService)); _uiDispatcher = uiDispatcher ?? throw new ArgumentNullException(nameof(uiDispatcher)); _iterateCommand = new SimpleCommand(IterateAsync, CanIterate); _cancelIterateCommand = new SimpleCommand(CancelIterate, CanCancelIterate); _changeRuleCommand = new SimpleCommand(ChangeRule, CanChangeRule); _gameService.CurrentGameChanged += (s, e) => _uiDispatcher.Invoke(() => ChangeGame(_gameService.CurrentGame)); if (_gameService.CurrentGame != null) { ChangeGame(_gameService.CurrentGame); } }
private void setupCommands() { if (EmbeddedModel is GenericCommandModel && (EmbeddedModel as GenericCommandModel).Command != null) { DoWorkCommand = (EmbeddedModel as GenericCommandModel).Command; DoWorkCommandParameter = (EmbeddedModel as GenericCommandModel).CommandParameter; } else { DoWorkCommand = new SimpleCommand { CanExecuteDelegate = x => EmbeddedModel.CanExecute(x), ExecuteDelegate = x => EmbeddedModel.Execute(x) } }; }
public void WhenExecutingFilterThenCacheIsChecked() { // Arrange CacheAttribute filter = this.CreateAttribute(); SimpleCommand command = new SimpleCommand { Property1 = 12, Property2 = "test" }; CommandHandlerRequest request = new CommandHandlerRequest(this.config, command); CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(SimpleCommand), typeof(SimpleCommandHandler)); CommandHandlerContext context = new CommandHandlerContext(request, descriptor); // Act filter.OnCommandExecuting(context); // Assert this.cache.Verify(c => c.Get(It.IsAny<string>(), It.IsAny<string>()), Times.Once()); Assert.Null(context.Response); }
private void CreateHeaderCommand() { // Create the command that the inserted header button will use. // When executed, the expandable region will be displayed. var command = new SimpleCommand { Action = () => mExpandableHeaderViewModel.LoadView(mExpandableRegionViewModel) }; // Set up the button content, and pass in the command to be used. mExtensibilityHelper.RegisterHeaderCommand( headerButtonCaption: SubsettingExampleStringResources.HeaderBarSubsettingButtonText, headerButtonTooltip: SubsettingExampleStringResources.HeaderBarSubsettingButtonTooltipText, buttonCommand: command, automationSuffix: "SubsettingExample"); }
public void When_testing_for_a_message_in_the_inbox() { //Arrange var inbox = new InMemoryInbox(); const string contextKey = "Developer_Test"; var command = new SimpleCommand(); //Act inbox.Add(command, contextKey); var exists = inbox.Exists <SimpleCommand>(command.Id, contextKey); //Assert exists.Should().BeTrue(); }
public JamEntryViewModel(JamEntry model) : base(model) { Team = new JamTeamViewModel(model.Team); ThumbnailPathProperty = ImageSourceProperty.CreateReadonly(this, nameof(Thumbnail), vm => vm.Model.ThumbnailPath); ThumbnailSmallPathProperty = ImageSourceProperty.CreateReadonly(this, nameof(ThumbnailSmall), vm => vm.Model.ThumbnailSmallPath); Launcher = new ProcessLauncher(); LaunchGameCommand = SimpleCommand.From(LaunchGame); OpenReadmeCommand = ReadmePath != null && !model.IsReadmePlease ? SimpleCommand.From(OpenReadme) : null; OpenReadmePleaseCommand = ReadmePath != null && model.IsReadmePlease ? SimpleCommand.From(OpenReadme) : null; OpenAfterwordCommand = AfterwordPath != null?SimpleCommand.From(OpenAfterword) : null; OpenDirectoryCommand = SimpleCommand.From(OpenDirectory); }
public DragDropItemViewModel(int value, bool isDroppable, bool isChildDroppable) { IsDroppable = isDroppable; IsChildDroppable = isChildDroppable; Value = value; UnselectAllCommand = new SimpleCommand() { ExecuteDelegate = (param) => { foreach (var item in Items) { item.IsSelected = false; } } }; }
public MvvmViewModel() { _model = new Board(); Cells = new ObservableCollection <Cell>(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Cells.Add(new Cell(i, j)); } } CellCommand = new SimpleCommand <string>(CellSelect); ResetCommand = new SimpleCommand(Reset); }
public void WhenExecutingFilterToIgnoreThenCacheIsIgnored() { // Arrange CacheAttribute filter = this.CreateAttribute(); SimpleCommand command = new SimpleCommand { Property1 = 12, Property2 = "test" }; SimpleCommand cachedCommand = new SimpleCommand { Property1 = 12, Property2 = "test in cache" }; CommandHandlerRequest request = new CommandHandlerRequest(this.config, command); CommandHandlerDescriptor descriptor = new CommandHandlerDescriptor(this.config, typeof(NotCachedCommand), typeof(NotCachedCommandHandler)); CommandHandlerContext context = new CommandHandlerContext(request, descriptor); this.cache.Setup(c => c.Get(It.IsAny<string>(), It.IsAny<string>())).Returns(new CacheAttribute.CacheEntry(cachedCommand)); // Act filter.OnCommandExecuting(context); // Assert this.cache.Verify(c => c.Get(It.IsAny<string>(), It.IsAny<string>()), Times.Never()); Assert.Null(context.Response); }
public MainWindowViewModel() : base("Shell", false, true) { _hearbeatIndex = new ConcurrentDictionary<string, Heartbeat>(); Mediator.GetInstance.RegisterInterest<Heartbeat>(Topic.ShellStateUpdated, HeartbeatReceived, TaskType.Periodic); HeartbeatLost = Visibility.Collapsed; Heartbeats = new ObservableCollection<SelectableDataItem>(); Themes = new ObservableCollection<SelectableDataItem> { new SelectableDataItem(Constants.ThemeAero), new SelectableDataItem(Constants.ThemeLuna), new SelectableDataItem(Constants.ThemeRoyale), //new SelectableDataItem(Constants.ThemeGold) // not ready }; ChangeThemeCommand = new SimpleCommand<Object, EventToCommandArgs>(ChangeTheme); ReloadCommand = new SimpleCommand<Object>(_ => { Heartbeat removed; _hearbeatIndex.TryRemove(StaleModule, out removed); HeartbeatLost = Visibility.Collapsed; Mediator.GetInstance.Broadcast(Topic.BootstrapperUnloadView, StaleModule); }); var timer = new Timer(_hr); timer.Elapsed += (s, e) => { var lostHeartbeats = _hearbeatIndex.Values .Where(i => (!i.NonRepeatable) && (DateTime.UtcNow - i.TimeCreated).TotalMilliseconds > _ht); foreach (var l in lostHeartbeats) { HeartbeatLost = Visibility.Visible; StaleModule = l.Key; Log.Warn(String.Format("Lost heartbeat from: {0}",l.Key)); } }; timer.Start(); }
public ShellViewModel( CreateOrderDialogViewModelFactory createOrderDialogViewModelFactory, IDialogService dialogService, OrderServiceInvoker orderServiceInvoker, IMessageBoxService messageBoxService, Func<OrdersViewModel> ordersViewModelFactory) { this.OrdersViewModel = ordersViewModelFactory(); this.createOrderDialogViewModelFactory = createOrderDialogViewModelFactory; this.dialogService = dialogService; this.orderServiceInvoker = orderServiceInvoker; this.messageBoxService = messageBoxService; StoreItems = new ObservableCollection<StoreItemViewModel>(); BindingOperations.EnableCollectionSynchronization(StoreItems, syncLock); CreateNewOrderCommand = new SimpleCommand<object, object>( CanExecuteCreateNewOrderCommand, ExecuteCreateNewOrderCommand); }
public HttpClientPageViewModel() : base(new HttpClientModel()) { GetCommand = new SimpleCommand(param => { RequestCommand = new SimpleCommand(Model.Get); SetButtonBrush("GET"); }); PostCommand = new SimpleCommand(param => { RequestCommand = new SimpleCommand(Model.Post); SetButtonBrush("POST"); }); PutCommand = new SimpleCommand(param => { RequestCommand = new SimpleCommand(Model.Put); SetButtonBrush("PUT"); }); DeleteCommand = new SimpleCommand(param => { RequestCommand = new SimpleCommand(Model.Delete); SetButtonBrush("DELETE"); }); }
private void CreateHeaderCommand() { var intentManager = mContainer.Resolve<IIntentManager>(); // Create the command that the inserted header button will use. var command = new SimpleCommand { Action = () => { var intent = new DomainToolsTabIntent(null, null); intentManager.Run(intent); } }; // Set up the button's content and pass in the command to be used. mExtensibilityHelper.RegisterHeaderCommand( headerButtonCaption: DomainToolsStringResources.GroupHeading, headerButtonTooltip: DomainToolsStringResources.GroupHeadingTooltip, buttonCommand: command); }
public MultiDownloadSelectionGrid() { InitializeComponent(); ToggleRowCommand= new SimpleCommand<object,Row>(ToggleRow); }
protected void _createCommands() { CommandToggleEnabled = new SimpleCommand() { ExecuteDelegate = o => { _event.Enabled = !_event.Enabled; _event.Save(); } }; }
public MainWindowViewModel() { CurrentDispatcher = Dispatcher.CurrentDispatcher; #region Commands initialization scanCommand = new SimpleCommand { ExecuteDelegate = x => Scan() }; cancelScanCommand = new SimpleCommand { ExecuteDelegate = x => CancelScan() }; checkDevicesGroupCommand = new SimpleCommand { ExecuteDelegate = CheckDevicesGroup }; checkDeviceCommand = new SimpleCommand { ExecuteDelegate = CheckDevice }; downloadDriversCommand = new SimpleCommand { ExecuteDelegate = x => DownloadDrivers() }; cancelDownloadDriversCommand = new SimpleCommand { ExecuteDelegate = x => CancelDownloadDrivers() }; composeCommand = new SimpleCommand { ExecuteDelegate = x => Compose() }; cancelComposeCommand = new SimpleCommand { ExecuteDelegate = x => CancelCompose() }; closeCommand = new SimpleCommand { ExecuteDelegate = x => Close() }; #endregion InitializeBackgroundWorker(); DownloadsDirectory = String.Format(@"{0}\Driver Utilites\Downloads", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); try { if (!Directory.Exists(DownloadsDirectory)) { Directory.CreateDirectory(DownloadsDirectory); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }