public async Task RefreshAsync()
        {
            _refreshCancellation?.Dispose();

            using (var cancellation = new CancellationDisposable())
            {
                _refreshCancellation = cancellation;
                refreshCommand?.RaiseCanExecuteChanged();

                try
                {
                    refreshCommand?.RaiseCanExecuteChanged();

                    await _definitions.RefreshAsync(cancellation.Token);
                }
                catch (OperationCanceledException)
                {
                }
                catch (Exception ex)
                {
                    // TODO LOG
                }

                _refreshCancellation = null;

                refreshCommand?.RaiseCanExecuteChanged();
            }
        }
        private void AddDevice(DeviceType device)
        {
            ISessionChoiceViewModel choice;

            if (Selection.TryGetSelectedItem(out choice) &&
                choice.SelectedDevices.IsReadOnly == false)
            {
                choice.SelectedDevices.Add(device);

                addDeviceCommand?.RaiseCanExecuteChanged();
                removeDeviceCommand?.RaiseCanExecuteChanged();
            }
        }
Exemple #3
0
        public MainViewModel(IStudentFaker studentFaker, IPersistentDataSource dataSource, ISchILDDataSource schILDDataSource, IIndex <string, IExportService> exportServices, IDispatcher dispatcher, IMessenger messenger)
            : base(messenger)
        {
            this.studentFaker     = studentFaker;
            this.dataSource       = dataSource;
            this.schILDDataSource = schILDDataSource;
            this.exportServices   = exportServices;
            this.dispatcher       = dispatcher;

            LoadStudentsCommand = new RelayCommand(LoadStudents, CanLoadStudents);
            SyncCommand         = new RelayCommand(Sync, CanSync);
            AnonymizeCommand    = new RelayCommand(Anonymize, CanAnonymize);
            AnonymizeSelectedStudentsCommand = new RelayCommand(AnomyizeSelectedStudents, CanAnonymizeSelectedStudents);
            RemoveNonActiveStudentsCommand   = new RelayCommand(RemoveNonActive, CanRemoveNonActive);
            RemoveSelectedStudentsCommand    = new RelayCommand(RemoveSelected, CanRemoveSelected);
            ExportCsvCommand        = new RelayCommand(ExportCsv, CanExport);
            ExportSchulITIdpCommand = new RelayCommand(ExportSchulITIdp, CanExport);

            Students.CollectionChanged += (sender, args) =>
            {
                AnonymizeCommand?.RaiseCanExecuteChanged();
                RemoveNonActiveStudentsCommand?.RaiseCanExecuteChanged();
                ExportCsvCommand?.RaiseCanExecuteChanged();
                ExportSchulITIdpCommand?.RaiseCanExecuteChanged();
            };

            SelectedStudents.CollectionChanged += (sender, args) =>
            {
                RemoveSelectedStudentsCommand?.RaiseCanExecuteChanged();
                AnonymizeSelectedStudentsCommand?.RaiseCanExecuteChanged();
            };

            dataSource.ConnectionStateChanged += (sender, args) =>
            {
                dispatcher.RunOnUI(() =>
                {
                    if (args.IsConnected == false)
                    {
                        // Clear all students in case we get disconnected
                        Students.Clear();
                        SelectedStudents.Clear();
                    }

                    IsNotPersistentDatabase = sender.IsInMemory;
                    LoadStudentsCommand?.RaiseCanExecuteChanged();
                    SyncCommand?.RaiseCanExecuteChanged();
                    AnonymizeCommand?.RaiseCanExecuteChanged();
                });
            };
        }
        public SettingsViewModel()
        {
            m_okCommand = new RelayCommand(Ok, CanOk);
            m_cancelCommand = new RelayCommand(Cancel);
            m_clearDatasheetsCacheCommand = new RelayCommand(ClearDatasheetsCache);
            m_clearImagesCacheCommand = new RelayCommand(ClearImagesCache);
            m_clearSavedDatasheetsCommand = new RelayCommand(ClearSavedDatasheets);
            m_checkUpdatesCommand = new RelayCommand(CheckUpdates);
            m_selectAppDataPathCommand = new RelayCommand(SelectAppDataPath);

            m_validators = new ValidatorCollection(() => m_okCommand.RaiseCanExecuteChanged());

            m_maxCacheSize = new IntegerValidator(0, 100000);
            m_maxCacheSize.ValidValue = (int)(Global.Configuration.MaxDatasheetsCacheSize / (1024 * 1024));
            m_validators.Add(m_maxCacheSize);

            LanguagePair pair = new LanguagePair(string.Empty);
            m_availableLanguages.Add(pair);
            m_selectedLanguage = pair;
            pair = new LanguagePair("en-US");
            if (Global.Configuration.Language == pair.Name) m_selectedLanguage = pair;
            m_availableLanguages.Add(pair);
            foreach (var langPath in Directory.EnumerateFiles(Global.LanguagesDirectory))
            {
                string[] tokens = Path.GetFileName(langPath).Split('.');
                if (tokens.Length < 2) continue;
                pair = new LanguagePair(tokens[1]);
                m_availableLanguages.Add(pair);
                if (pair.Name == Global.Configuration.Language) m_selectedLanguage = pair;
            }

            m_initialPath = AppDataPath = Global.AppDataPath;
            m_favouritesOnStart = Global.Configuration.FavouritesOnStart;
        }
        public void RaisingCanExecuteChangedRaisesCanExecuteChanged()
        {
            var command = new RelayCommand(o => { });
            command.MonitorEvents();

            command.RaiseCanExecuteChanged();

            command.ShouldRaise("CanExecuteChanged");
        }
 private void SelectedResults_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
 {
     SaveSelected.RaiseCanExecuteChanged();
     RaisePropertyChanged(nameof(EditSelected));
     _editSelected?.RaiseCanExecuteChanged();
     RaisePropertyChanged(nameof(SendSelectedImageToClipboard));
     RaisePropertyChanged(nameof(SendSelectedScaledImageToClipboard));
     RaisePropertyChanged(nameof(SendSelectedTextToClipboard));
     _sendSelectedToClipboard?.RaiseCanExecuteChanged();
 }
        public ComponentTitleViewModel(string title, IWindowService windowService)
        {
            if (windowService == null) throw new ArgumentNullException(nameof(windowService));

            _title = title;
            _oldTitle = title;

            _windowService = windowService;

            ConfirmCommand = new RelayCommand(ExecuteConfirmCommand, CanCloseDialog);
            CancelCommand = new RelayCommand(ExecuteCancelCommand);

            this.ForProperty(nameof(Title))
                .Subscribe(() => { ConfirmCommand.RaiseCanExecuteChanged(); });
        }
        private EditPartViewModel()
        {
            m_okCommand = new RelayCommand(Ok);
            m_cancelCommand = new RelayCommand(Cancel);
            m_refreshCommand = new RelayCommand(Refresh, CanRefresh);
            m_rebuildTagsCommand = new RelayCommand(RebuildTags);
            m_selectImageCommand = new RelayCommand(SelectImage);

            m_validators = new ValidatorCollection(() => m_okCommand.RaiseCanExecuteChanged());

            m_name = new NoWhitespaceValidator();
            m_validators.Add(m_name);

            m_tags = new SeparatedValuesValidator(',');
            m_validators.Add(m_tags);
        }
Exemple #9
0
        public void Given_CanExecuteDelegate_When_RaiseCanExecuteCalled_EventFires()
        {
            var eventFired = false;
            var handler = new EventHandler((o, e) =>
            {
                eventFired = true;
            });

            var sut = new RelayCommand<object>(Delegate1, CanChange);
            sut.CanExecuteChanged += handler;

            sut.RaiseCanExecuteChanged();

            Assert.IsTrue(eventFired);

            sut.CanExecuteChanged -= handler;
        }
Exemple #10
0
        private bool NewMethod()
        {
            tester = !tester;
            if (tester)
            {
                ThemeManager.SetCustomTheme(new System.Uri("/UnderDev;component/CustomThemeResources.xaml", System.UriKind.Relative), Theme.Light);
                ThemeManager.ToLightTheme();
            }
            else
            {
                ThemeManager.SetCustomTheme(new System.Uri("/UnderDev;component/LightThemeResources.xaml", System.UriKind.Relative), Theme.Light);
                ThemeManager.ToLightTheme();
            }

            B1.RaiseCanExecuteChanged();
            B2.RaiseCanExecuteChanged();
            return(tester);
        }
Exemple #11
0
        public void TestRaiseCanExecuteChanged()
        {
            var          calls   = new List <(object sender, EventArgs e)>();
            EventHandler handler = (sender, e) =>
            {
                calls.Add((sender, e));
            };

            var cmd = new RelayCommand(() => { });

            cmd.CanExecuteChanged += handler;

            cmd.RaiseCanExecuteChanged();

            Assert.AreEqual(1, calls.Count);
            Assert.AreSame(cmd, calls[0].sender);
            Assert.AreSame(EventArgs.Empty, calls[0].e);
        }
Exemple #12
0
        private void OnDataChanged()
        {
            if (MainItemsSource == null)
            {
                return;
            }
            var cells       = UniformGridColumns * UniformGridRows;
            var enumerable  = (MainItemsSource as IEnumerable <object>)?.ToArray();
            var itemsSource = enumerable.Skip(_pageIndex * cells).Take(cells);

            _isEnd = enumerable != null && enumerable.Count() <= cells * (_pageIndex + 1);
            _previousPageCommand?.RaiseCanExecuteChanged();
            _nextPageCommand?.RaiseCanExecuteChanged();

            if (Orientation == Orientation.Vertical)
            {
                var finished             = false;
                var itemsSourceArray     = itemsSource.ToArray();
                var reorderedItemsSource = new List <object>();
                for (var i = 0; i < UniformGridRows; i++)
                {
                    for (var j = 0; j < UniformGridColumns; j++)
                    {
                        var arrayIndex = i + j * UniformGridColumns;
                        reorderedItemsSource.Add((arrayIndex < itemsSource.Count()) ? itemsSourceArray[j + i] : null);
                        if (arrayIndex + 1 == itemsSource.Count())
                        {
                            finished = true;
                            break;
                        }
                    }
                    if (finished)
                    {
                        break;
                    }
                }
                ItemsSource = reorderedItemsSource;
            }
            else
            {
                ItemsSource = itemsSource;
            }
        }
        private void Validate()
        {
            bool hasErrorBefore = HasErrors;

            _parameterError = _originalParameter == Parameter ||
                              string.IsNullOrEmpty(_originalParameter) && string.IsNullOrEmpty(Parameter)
                ? "Change parameter before update"
                : null;

            _applyCommand.RaiseCanExecuteChanged();
            if (hasErrorBefore != HasErrors)
            {
                var handler = ErrorsChanged;
                if (handler != null)
                {
                    handler(this, new DataErrorsChangedEventArgs("Parameter"));
                }
            }
        }
Exemple #14
0
        public void CanExecuteTest()
        {
            bool executed   = false;
            bool canExecute = false;

            var target = new RelayCommand(() => executed = false, () => canExecute);

            if (executed)
            {
            }

            Assert.IsFalse(target.CanExecute(null));
            canExecute = true;
            Assert.IsTrue(target.CanExecute(null));

            AssertHelper.CanExecuteChangedEvent(target, () => target.RaiseCanExecuteChanged());

            Assert.IsTrue(target.CanExecute(null));
        }
Exemple #15
0
        private void ExecuteActiveCommand(OperatorDto param)
        {
            IsBusy = true;
            Action action = () => CommunicateManager.Invoke <IBusinessmanService>(p =>
            {
                p.ModifyOperatorState(param.Account);

                Refresh(param);
            }, UIManager.ShowErr);

            Task.Factory.StartNew(action).ContinueWith(task =>
            {
                DispatcherHelper.UIDispatcher.Invoke(new Action(() =>
                {
                    IsBusy = false;
                    ActiveCommand.RaiseCanExecuteChanged();
                }));
            });
        }
Exemple #16
0
        public static RelayCommand <T> DependentOn <T>(this RelayCommand <T> command, INotifyPropertyChanged owner, params string[] properties)
        {
            if (owner == null || properties == null || properties.Length == 0)
            {
                return(command);
            }

            var propertiesSet = new HashSet <string>(properties);

            owner.PropertyChanged += (sender, e) =>
            {
                if (propertiesSet.Contains(e.PropertyName))
                {
                    command.RaiseCanExecuteChanged();
                }
            };

            return(command);
        }
Exemple #17
0
 private void RaisePropertyChangedAll()
 {
     _saveCommand?.RaiseCanExecuteChanged();
     _revertCommand?.RaiseCanExecuteChanged();
     _exitCommand?.RaiseCanExecuteChanged();
     _fontSizeIncreaseCommand?.RaiseCanExecuteChanged();
     _fontSizeDecreaseCommand?.RaiseCanExecuteChanged();
     _boldFontCommand?.RaiseCanExecuteChanged();
     _italicsFontCommand?.RaiseCanExecuteChanged();
     _underlineFontCommand?.RaiseCanExecuteChanged();
     _leftAlignTextCommand?.RaiseCanExecuteChanged();
     _rightAlignTextCommand?.RaiseCanExecuteChanged();
     _centerAlignTextCommand?.RaiseCanExecuteChanged();
     _undoCommand?.RaiseCanExecuteChanged();
     _redoCommand?.RaiseCanExecuteChanged();
     _copyCommand?.RaiseCanExecuteChanged();
     _pasteCommand?.RaiseCanExecuteChanged();
     _deleteCommand?.RaiseCanExecuteChanged();
 }
        public Group101SettingsViewModel(IUserInterfaceRoot uiRoot, ILogger logger,
                                         IAinSettingsReaderWriter readerWriter, IAinSettingsReadNotify ainSettingsReadNotify,
                                         IAinSettingsStorage storage, IAinSettingsStorageUpdatedNotify storageUpdatedNotify,
                                         IAinsCounter ainsCounter)
        {
            _uiRoot                = uiRoot;
            _logger                = logger;
            _readerWriter          = readerWriter;
            _ainSettingsReadNotify = ainSettingsReadNotify;
            _storage               = storage;
            _storageUpdatedNotify  = storageUpdatedNotify;
            _ainsCounter           = ainsCounter;

            Parameter01Vm =
                new ParameterDecimalEditCheckViewModel("101.01. Пропорциональный коэф. регулятора потока, Flux Kp",
                                                       "f8", -128.0m, 127.99609375m)
            {
                Increment = 0.00390625m
            };
            Parameter02Vm =
                new ParameterDecimalEditCheckViewModel("101.02. Интегральный коэф. регулятора потока, Flux Ki", "f6",
                                                       -128.0m, 128.0m)
            {
                Increment = 0.000001m
            };                                                // min step = 1 / 16777216.0 = 0,000000059604644775390625

            Parameter03Vm = new ParameterDecimalEditCheckViewModel("101.03. Мин. ограничение выхода регулятора потока",
                                                                   "f0", -10000, 10000);
            Parameter04Vm = new ParameterDecimalEditCheckViewModel("101.04. Макс. ограничение выхода регулятора потока",
                                                                   "f0", -10000, 10000);

            ReadSettingsCmd  = new RelayCommand(ReadSettings, () => true); // TODO: read only when connected to COM
            WriteSettingsCmd =
                new RelayCommand(WriteSettings, () => IsWriteEnabled);     // TODO: read only when connected to COM

            _ainSettingsReadNotify.AinSettingsReadComplete += AinSettingsReadNotifyOnAinSettingsReadComplete;

            _storageUpdatedNotify.AinSettingsUpdated += (zbAinNuber, settings) =>
            {
                _uiRoot.Notifier.Notify(() => WriteSettingsCmd.RaiseCanExecuteChanged());
            };
        }
        public NewSaleViewModel(IUnitOfWork ctx)
        {
            _context              = ctx;
            stores                = new ObservableCollection <Store>(_context.Stores.GetAll());
            products              = new ObservableCollection <Product>(_context.Products.GetAll());
            selectedProduct       = null;
            selectedStore         = null;
            amount                = 0;
            SaveCommand           = new RelayCommand(SaveSale, canSave);
            this.PropertyChanged += (s, e) => SaveCommand.RaiseCanExecuteChanged();

            MessengerInstance.Register <Messages.ProductAddedMessage>(this, (msg) =>
            {
                products.Add(msg.product);
            });
            MessengerInstance.Register <Messages.StoreAddedMessage>(this, (msg) =>
            {
                stores.Add(msg.store);
            });
        }
Exemple #20
0
        void SceneExecAdd()
        {
            SceneAddMode = true;

            CurrentScene            = new Scene();
            CurrentScene.Partition  = AppContext.Partition;
            CurrentScene.LightZones = new ObservableCollection <LightZone>();

            SceneAddCmd.RaiseCanExecuteChanged();
            SceneRemoveCmd.RaiseCanExecuteChanged();

            SceneObjectPanelVisibility   = Visibility.Visible;
            SceneObjectButtonsVisibility = Visibility.Visible;
            SceneObjectCurtainVisibility = Visibility.Collapsed;

            SceneListVisibility        = Visibility.Hidden;
            SceneListCurtainVisibility = Visibility.Visible;

            MessengerInstance.Send("", AppContext.BlockUIMsg);
        }
        public static RelayCommand ObservesProperty <T>(this RelayCommand command, Expression <Func <T> > propertyExpression)
        {
            MemberExpression expr_18 = propertyExpression.Body as MemberExpression;

            if (expr_18 == null)
            {
                throw new ArgumentException("Only member expressions are supported");
            }
            ConstantExpression expr_30 = expr_18.Expression as ConstantExpression;

            if (expr_30 == null)
            {
                throw new ArgumentException("Non constant expression are not supported");
            }
            ((INotifyPropertyChanged)expr_30.Value).PropertyChanged += delegate(object s, PropertyChangedEventArgs e)
            {
                command.RaiseCanExecuteChanged();
            };
            return(command);
        }
Exemple #22
0
 private async void OnExecuteWriteLocalValuesToDevice()
 {
     try
     {
         SetQueriesLock(true);
         this.WriteConfigurationCommand.RaiseCanExecuteChanged();
         if (LocalValuesWriteValidator.ValidateLocalValuesToWrite(_runtimeConfigurationViewModel
                                                                  .RootConfigurationItemViewModels))
         {
             await new MemoryWriterVisitor(_runtimeConfigurationViewModel.DeviceContext, new List <ushort>(),
                                           _deviceConfiguration, 0).ExecuteWrite();
         }
     }
     finally
     {
         SetQueriesLock(false);
         WriteConfigurationCommand.RaiseCanExecuteChanged();
         TryUpdateTable();
     }
 }
Exemple #23
0
        public CredentialsViewModel(string username)
        {
            LoginCommand          = new RelayCommand(Accept, () => IsValid);
            CancelCommand         = new RelayCommand(Cancel);
            ForgotPasswordCommand = new RelayCommand(() => BrowserHelper.OpenDefaultBrowser(BitbucketResources.PasswordResetUrl));
            SignUpCommand         = new RelayCommand(() => BrowserHelper.OpenDefaultBrowser(BitbucketResources.SignUpLinkUrl));

            LoginValidator    = PropertyValidator.For(this, x => x.Login).Required(BitbucketResources.LoginRequired);
            PasswordValidator = PropertyValidator.For(this, x => x.Password).Required(BitbucketResources.PasswordRequired);

            _modelValidator.Add(LoginValidator);
            _modelValidator.Add(PasswordValidator);
            _modelValidator.IsValidChanged += (s, e) => LoginCommand.RaiseCanExecuteChanged();

            // Set last to allow validator to run
            if (!string.IsNullOrWhiteSpace(username))
            {
                Login = username;
            }
        }
        public void SetValueShouldUpdateIsEnabledPropertyOneTimeModeAfterDispose()
        {
            bool canExecute = false;
            var command = new RelayCommand(o => { }, o => canExecute, this);

            var srcAccessor = new BindingSourceAccessorMock();
            var source = new BindingSourceModel();
            var ctx = new DataContext(BindingBuilderConstants.Behaviors.ToValue(new List<IBindingBehavior> { new OneTimeBindingMode() }));
            var accessor = GetAccessor(source, BindingSourceModel.EventName, ctx, false);
            srcAccessor.GetValue = (info, context, arg3) => command;
            accessor.SetValue(srcAccessor, EmptyContext, true);
            accessor.Dispose();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            source.IsEnabled.ShouldBeFalse();
            canExecute = true;
            command.RaiseCanExecuteChanged();
            source.IsEnabled.ShouldBeTrue();
        }
Exemple #25
0
 private void UpdateCommands()
 {
     RaisePropertyChanged(nameof(EditSelected));
     _editSelected?.RaiseCanExecuteChanged();
     RaisePropertyChanged(nameof(SendSelectedImageToClipboard));
     RaisePropertyChanged(nameof(SendSelectedScaledImageToClipboard));
     RaisePropertyChanged(nameof(SendSelectedTextToClipboard));
     _sendSelectedToClipboard?.RaiseCanExecuteChanged();
     CloneSelected.RaiseCanExecuteChanged();
     RaisePropertyChanged(nameof(CloneSelectedToolTip));
     CopySelected.RaiseCanExecuteChanged();
     RaisePropertyChanged(nameof(CopySelectedToolTip));
     MoveSelected.RaiseCanExecuteChanged();
     RaisePropertyChanged(nameof(MoveSelectedToolTip));
     ExportSelected.RaiseCanExecuteChanged();
     RaisePropertyChanged(nameof(ExportSelectedToolTip));
     DeleteSelected.RaiseCanExecuteChanged();
     RaisePropertyChanged(nameof(DeleteSelectedToolTip));
     ResetStylesSelected.RaiseCanExecuteChanged();
     RaisePropertyChanged(nameof(ResetStylesSelectedToolTip));
 }
 private void UpdateCommands()
 {
     RaisePropertyChanged("EditSelected");
     _editSelected?.RaiseCanExecuteChanged();
     RaisePropertyChanged("SendSelectedImageToClipboard");
     RaisePropertyChanged("SendSelectedScaledImageToClipboard");
     RaisePropertyChanged("SendSelectedTextToClipboard");
     _sendSelectedToClipboard?.RaiseCanExecuteChanged();
     CloneSelected.RaiseCanExecuteChanged();
     RaisePropertyChanged("CloneSelectedToolTip");
     CopySelected.RaiseCanExecuteChanged();
     RaisePropertyChanged("CopySelectedToolTip");
     MoveSelected.RaiseCanExecuteChanged();
     RaisePropertyChanged("MoveSelectedToolTip");
     ExportSelected.RaiseCanExecuteChanged();
     RaisePropertyChanged("ExportSelectedToolTip");
     DeleteSelected.RaiseCanExecuteChanged();
     RaisePropertyChanged("DeleteSelectedToolTip");
     ResetStylesSelected.RaiseCanExecuteChanged();
     RaisePropertyChanged("ResetStylesSelectedToolTip");
 }
        public void AccessorShouldUseCommandParameterCanExecute()
        {
            bool isInvoked = false;
            var parameter = new object();
            var command = new RelayCommand(o => { }, o =>
            {
                o.ShouldEqual(parameter);
                isInvoked = true;
                return false;
            }, this);
            var srcAccessor = new BindingSourceAccessorMock();
            var source = new BindingSourceModel();
            var accessor = GetAccessor(source, BindingSourceModel.EventName, EmptyContext, false, d => parameter);
            srcAccessor.GetValue = (info, context, arg3) => command;

            accessor.SetValue(srcAccessor, EmptyContext, true);
            isInvoked.ShouldBeTrue();

            isInvoked = false;
            command.RaiseCanExecuteChanged();
            isInvoked.ShouldBeTrue();
        }
Exemple #28
0
        /// <summary>
        /// Save new expense and return to mainpage.
        /// </summary>
        private async void SaveExpenseExecute()
        {
            if (string.IsNullOrWhiteSpace(this.expense.Name))
            {
                this.validations.TitleFailed = true;
            }

            if (string.IsNullOrWhiteSpace(this.expense.Description))
            {
                this.validations.DescriptionFailed = true;
            }

            double amount;

            this.validations.AmountFailed = !double.TryParse(this.expenseAmount, out amount);

            if (this.CanSaveExpenses())
            {
                this.IsBusy = true;
                saveExpenseCommand.RaiseCanExecuteChanged();

                this.expense.ExpenseType      = this.type;
                this.expense.EmployeeId       = AppSettings.EmployeeInformation.EmployeeId;
                this.expense.CreationDate     = DateTime.UtcNow;
                this.expense.LastModifiedDate = DateTime.UtcNow;
                this.expense.Amount           = amount;

                if (this.ExpensePhoto != null)
                {
                    this.expense.Picture = this.ExpensePhoto;
                }
                this.expense.Status = ExpenseStatus.Pending;
                await this.myCompanyClient.ExpenseService.Add(Expense);

                MessengerInstance.Send <ReloadHistoryMessage>(new ReloadHistoryMessage());
                this.IsBusy = false;
                this.navService.NavigateBack();
            }
        }
Exemple #29
0
        public void AccessorShouldToggleEnabledFalse()
        {
            bool canExecute = false;
            bool isInvoked  = false;
            var  parameter  = new object();
            var  command    = new RelayCommand(o => { }, o =>
            {
                o.ShouldEqual(parameter);
                isInvoked = true;
                return(canExecute);
            }, this);
            bool isEnabled = true;
            IAttachedBindingMemberInfo <object, bool> member =
                AttachedBindingMember.CreateMember <object, bool>(AttachedMemberConstants.Enabled,
                                                                  (info, o) => isEnabled,
                                                                  (info, o, v) => isEnabled = v);
            var memberProvider = new BindingMemberProvider();

            memberProvider.Register(typeof(object), member, false);
            BindingServiceProvider.MemberProvider = memberProvider;

            var srcAccessor = new BindingSourceAccessorMock();
            var source      = new BindingSourceModel();
            var accessor    = GetAccessor(source, BindingSourceModel.EventName, new DataContext(BindingBuilderConstants.ToggleEnabledState.ToValue(false)), false, d => parameter);

            srcAccessor.GetValue = (info, context, arg3) => command;

            isEnabled.ShouldBeTrue();
            accessor.SetValue(srcAccessor, EmptyContext, true);
            isInvoked.ShouldBeFalse();
            isEnabled.ShouldBeTrue();

            isInvoked  = false;
            canExecute = true;
            command.RaiseCanExecuteChanged();
            isInvoked.ShouldBeFalse();
            isEnabled.ShouldBeTrue();
        }
Exemple #30
0
        private void RefreshGUI()
        {
            OnPropertyChanged("FireworkManager");

            //Careful must be called from UI Thread
            _userControlDispatcher.Invoke(() =>
            {
                if (_startTestingReceptorCommand != null)
                {
                    _startTestingReceptorCommand.RaiseCanExecuteChanged();
                }

                if (_stopTestingReceptorCommand != null)
                {
                    _stopTestingReceptorCommand.RaiseCanExecuteChanged();
                }

                if (_testConductiviteCommand != null)
                {
                    _testConductiviteCommand.RaiseCanExecuteChanged();
                }
            });
        }
Exemple #31
0
        private async void LoadImage(object ob)
        {
            var task = Task.Factory.StartNew(() =>
            {
                Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
                openFileDialog.Filter = "PNG Files (*.png)|*.png|JPEG Files (*.jpeg)|*.jpeg|JPG Files (*.jpg)|";
                if (openFileDialog.ShowDialog() == true && openFileDialog.CheckPathExists)
                {
                    OriginalPictureHost = new Picture(openFileDialog.FileName);
                    Path = openFileDialog.FileName;
                    IsSpecificColorTriangleDetecionChecked = false;

                    //TO DO:
                    //that can be new EmptyTriangleDetector() object -->
                    SpecificTriangleDetector = new ColoredTriangleDetector()
                    {
                        Picture = new Picture(openFileDialog.FileName)
                    };
                }
                _specificColorTriangleDetectionCommad.RaiseCanExecuteChanged();
            });
            await task;
        }
Exemple #32
0
        public GroupDetailVm(IMediator mediator, IResourceProxy resource, INavigationService navigation, IDialogService dialog, INotificationService notification)
        {
            _mediator     = mediator;
            _resource     = resource;
            _navigation   = navigation;
            _dialog       = dialog;
            _notification = notification;

            SaveCommand        = new RelayCommand(async() => await SaveChanges(), () => Database.IsDirty);
            SortEntriesCommand = new RelayCommand(async() => await SortEntriesAsync(), () => IsEditMode);
            SortGroupsCommand  = new RelayCommand(async() => await SortGroupsAsync(), () => IsEditMode);
            MoveCommand        = new RelayCommand <string>(async destination => await Move(destination), destination => IsNotRoot && !string.IsNullOrEmpty(destination) && destination != Id);
            CreateEntryCommand = new RelayCommand(async() => await AddNewEntry(), () => !IsInRecycleBin && Database.RecycleBinId != Id);
            CreateGroupCommand = new RelayCommand <string>(async newGroupName => await AddNewGroup(newGroupName), _ => !IsInRecycleBin && Database.RecycleBinId != Id);
            DeleteCommand      = new RelayCommand(async() => await AskForDelete(), () => IsNotRoot);
            GoBackCommand      = new RelayCommand(() => _navigation.GoBack());
            GoToParentCommand  = new RelayCommand(() => GoToGroup(Parent.Id), () => Parent != null);
            GoToGroupCommand   = new RelayCommand <GroupVm>(group => GoToGroup(group.Id), group => group != null);
            GoToEntryCommand   = new RelayCommand <EntryVm>(entry => GoToEntry(entry.Id), entry => entry != null);
            DeleteEntryCommand = new RelayCommand <EntryVm>(async entry => await AskForDeleteEntry(entry), entry => entry != null);

            MessengerInstance.Register <DatabaseSavedMessage>(this, _ => SaveCommand.RaiseCanExecuteChanged());
        }
Exemple #33
0
        public SettingsViewModel(IPersistentDataSource persistentDataSource, ISchILDDataSource schILDDataSource, ISettingsService settingsService, IMessenger messenger)
            : base(messenger)
        {
            this.persistentDataSource = persistentDataSource;
            this.schILDDataSource     = schILDDataSource;
            this.settingsService      = settingsService;

            TestSchILDConnectionCommand     = new RelayCommand(TestConnectSchILD, CanTestConnectSchILD);
            TestDataSourceConnectionCommand = new RelayCommand(TestConnectDataSource, TestCanConnectDataSource);
            ConnectDataSourceCommand        = new RelayCommand(ConnectDataSource, CanConnectDataSource);

            AddDatabaseTypes();
            AddAnonymizationTypes();

            LoadSettings();

            settingsService.Changed += delegate
            {
                TestSchILDConnectionCommand?.RaiseCanExecuteChanged();
                TestDataSourceConnectionCommand?.RaiseCanExecuteChanged();
                ConnectDataSourceCommand?.RaiseCanExecuteChanged();
            };
        }
Exemple #34
0
        public SoloRunViewModel() : base()
        {
            StartRun = new RelayCommand(() => {
                RunManager.Instance.Start();
                StopRun.RaiseCanExecuteChanged();
                StartRun.RaiseCanExecuteChanged();
            },
                                        () => { return(!RunManager.Instance.InRun /*&& BandService.Instance.IsConnected*/); });

            StopRun = new RelayCommand(() =>
            {
                RunManager.Instance.Stop();
                StopRun.RaiseCanExecuteChanged();
                StartRun.RaiseCanExecuteChanged();
            },
                                       () => { return(RunManager.Instance.InRun); });

            RunManager.Instance.OnRouteUpdate         += Instance_OnRouteUpdate;
            LocationService.Instance.OnLocationChange += Instance_OnLocationChange;
            BandService.Instance.OnHeartRateChange    += Instance_OnHeartRateChange;

            CurrentLocation = ExtentionMethods.GetDefaultPoint();
        }
Exemple #35
0
 public MainViewModel()
 {
     keyDictionary = new Dictionary <string, IntPtr>();
     keyDictionary.Add("1", (IntPtr)(Keys.D1));
     keyDictionary.Add("2", (IntPtr)(Keys.D2));
     keyDictionary.Add("3", (IntPtr)(Keys.D3));
     keyDictionary.Add("4", (IntPtr)(Keys.D4));
     keyDictionary.Add("5", (IntPtr)(Keys.D5));
     keyDictionary.Add("6", (IntPtr)(Keys.D6));
     keyDictionary.Add("7", (IntPtr)(Keys.D7));
     keyDictionary.Add("8", (IntPtr)(Keys.D8));
     keyDictionary.Add("9", (IntPtr)(Keys.D9));
     keyDictionary.Add("0", (IntPtr)(Keys.D0));
     keyDictionary.Add("space", (IntPtr)(Keys.Space));
     keyDictionary.Add("-", (IntPtr)(Keys.OemMinus));
     keyDictionary.Add("=", (IntPtr)(Keys.Oemplus));
     StartCommand       = new RelayCommand(StartKeySpam, CanStartExecute);
     LoadSettingCommand = new RelayCommand(LoadSetting, CanLoadSettingExecute);
     StopCommand        = new RelayCommand(StopKeySpam, CanStopExecute);
     StartCommand.RaiseCanExecuteChanged();
     delayTime     = 1;
     delayTimeList = new List <int>();
     LoadSetting();
 }
        public void AccessorShouldUseOnlyOneCmd()
        {
            bool isEnabled = false;
            var oldCmd = new RelayCommand(o => { }, o => false, this);
            var command = new RelayCommand(o => { }, o => isEnabled, this);
            var srcAccessor = new BindingSourceAccessorMock();
            var source = new BindingSourceModel();
            var accessor = GetAccessor(source, BindingSourceModel.EventName, EmptyContext, false);
            srcAccessor.GetValue = (info, context, arg3) => oldCmd;

            accessor.SetValue(srcAccessor, EmptyContext, true);
            source.IsEnabled.ShouldBeFalse();
            oldCmd.RaiseCanExecuteChanged();
            source.IsEnabled.ShouldBeFalse();

            srcAccessor.GetValue = (info, context, arg3) => command;
            accessor.SetValue(srcAccessor, EmptyContext, true);
            isEnabled = true;
            command.RaiseCanExecuteChanged();
            source.IsEnabled.ShouldEqual(isEnabled);

            oldCmd.RaiseCanExecuteChanged();
            source.IsEnabled.ShouldEqual(isEnabled);

            srcAccessor.GetValue = (info, context, arg3) => null;
            accessor.SetValue(srcAccessor, EmptyContext, true);
            isEnabled = false;
            command.RaiseCanExecuteChanged();
            source.IsEnabled.ShouldBeTrue();
        }
        public MainWindowViewModel(IItemFilterScriptRepository itemFilterScriptRepository,
                                   IItemFilterScriptTranslator itemFilterScriptTranslator,
                                   IReplaceColorsViewModel replaceColorsViewModel,
                                   IAvalonDockWorkspaceViewModel avalonDockWorkspaceViewModel,
                                   ISettingsPageViewModel settingsPageViewModel,
                                   IThemeProvider themeProvider,
                                   IThemeService themeService,
                                   IMessageBoxService messageBoxService,
                                   IClipboardService clipboardService)
        {
            _itemFilterScriptRepository = itemFilterScriptRepository;
            _itemFilterScriptTranslator = itemFilterScriptTranslator;
            _replaceColorsViewModel = replaceColorsViewModel;
            _avalonDockWorkspaceViewModel = avalonDockWorkspaceViewModel;
            SettingsPageViewModel = settingsPageViewModel;
            _themeProvider = themeProvider;
            _themeService = themeService;
            _messageBoxService = messageBoxService;
            _clipboardService = clipboardService;

            NewScriptCommand = new RelayCommand(OnNewScriptCommand);
            CopyScriptCommand = new RelayCommand(OnCopyScriptCommand, () => ActiveDocumentIsScript);
            OpenScriptCommand = new RelayCommand(async () => await OnOpenScriptCommand());
            OpenThemeCommand = new RelayCommand(async () => await OnOpenThemeCommandAsync());

            SaveCommand = new RelayCommand(async () => await OnSaveDocumentCommandAsync(), ActiveDocumentIsEditable);
            SaveAsCommand = new RelayCommand(async () => await OnSaveAsCommandAsync(), ActiveDocumentIsEditable);
            CloseCommand = new RelayCommand(OnCloseDocumentCommand, ActiveDocumentIsEditable);

            CopyBlockCommand = new RelayCommand(OnCopyBlockCommand, () => ActiveDocumentIsScript && ActiveScriptHasSelectedBlock);
            CopyBlockStyleCommand = new RelayCommand(OnCopyBlockStyleCommand, () => ActiveDocumentIsScript && ActiveScriptHasSelectedBlock);
            PasteCommand = new RelayCommand(OnPasteCommand, () => ActiveDocumentIsScript && ActiveScriptHasSelectedBlock);
            PasteBlockStyleCommand = new RelayCommand(OnPasteBlockStyleCommand, () => ActiveDocumentIsScript && ActiveScriptHasSelectedBlock);

            MoveBlockUpCommand = new RelayCommand(OnMoveBlockUpCommand, () => ActiveDocumentIsScript && ActiveScriptHasSelectedBlock);
            MoveBlockDownCommand = new RelayCommand(OnMoveBlockDownCommand, () => ActiveDocumentIsScript && ActiveScriptHasSelectedBlock);
            MoveBlockToTopCommand = new RelayCommand(OnMoveBlockToTopCommand, () => ActiveDocumentIsScript && ActiveScriptHasSelectedBlock);
            MoveBlockToBottomCommand = new RelayCommand(OnMoveBlockToBottomCommand, () => ActiveDocumentIsScript && ActiveScriptHasSelectedBlock);

            AddBlockCommand = new RelayCommand(OnAddBlockCommand, () => ActiveDocumentIsScript);
            AddSectionCommand = new RelayCommand(OnAddSectionCommand, () => ActiveDocumentIsScript);
            DeleteBlockCommand = new RelayCommand(OnDeleteBlockCommand, () => ActiveDocumentIsScript && ActiveScriptHasSelectedBlock);
            DisableBlockCommand = new RelayCommand(OnDisableBlockCommand, () => ActiveDocumentIsScript && ActiveScriptHasSelectedEnabledBlock);
            EnableBlockCommand = new RelayCommand(OnEnableBlockCommand, () => ActiveDocumentIsScript && ActiveScriptHasSelectedDisabledBlock);
            OpenAboutWindowCommand = new RelayCommand(OnOpenAboutWindowCommand);
            ReplaceColorsCommand = new RelayCommand(OnReplaceColorsCommand, () => ActiveDocumentIsScript);

            CreateThemeCommand = new RelayCommand(OnCreateThemeCommand, () => ActiveDocumentIsScript);
            ApplyThemeToScriptCommand = new RelayCommand(async () => await OnApplyThemeToScriptCommandAsync(), () => ActiveDocumentIsScript);
            EditMasterThemeCommand = new RelayCommand(OnEditMasterThemeCommand, () => ActiveDocumentIsScript);

            AddTextColorThemeComponentCommand = new RelayCommand(OnAddTextColorThemeComponentCommand, () => ActiveDocumentIsTheme && ActiveThemeIsEditable);
            AddBackgroundColorThemeComponentCommand = new RelayCommand(OnAddBackgroundColorThemeComponentCommand, () => ActiveDocumentIsTheme && ActiveThemeIsEditable);
            AddBorderColorThemeComponentCommand = new RelayCommand(OnAddBorderColorThemeComponentCommand, () => ActiveDocumentIsTheme && ActiveThemeIsEditable);
            DeleteThemeComponentCommand = new RelayCommand(OnDeleteThemeComponentCommand, () => ActiveDocumentIsTheme && ActiveThemeIsEditable && _avalonDockWorkspaceViewModel.ActiveThemeViewModel.SelectedThemeComponent != null);

            ExpandAllBlocksCommand = new RelayCommand(OnExpandAllBlocksCommand, () => ActiveDocumentIsScript);
            CollapseAllBlocksCommand = new RelayCommand(OnCollapseAllBlocksCommand, () => ActiveDocumentIsScript);

            ToggleShowAdvancedCommand = new RelayCommand<bool>(OnToggleShowAdvancedCommand, s => ActiveDocumentIsScript);
            ClearFiltersCommand = new RelayCommand(OnClearFiltersCommand, () => ActiveDocumentIsScript);

            if (string.IsNullOrEmpty(_itemFilterScriptRepository.GetItemFilterScriptDirectory()))
            {
                SetItemFilterScriptDirectory();
            }

            var icon = new BitmapImage();
            icon.BeginInit();
            icon.UriSource = new Uri("pack://application:,,,/Filtration;component/Resources/Icons/filtration_icon.png");
            icon.EndInit();
            Icon = icon;

            Messenger.Default.Register<ThemeClosedMessage>(this, message =>
            {
                if (message.ClosedViewModel == null) return;
                AvalonDockWorkspaceViewModel.CloseDocument(message.ClosedViewModel);
            });

            Messenger.Default.Register<NotificationMessage>(this, message =>
            {
                switch (message.Notification)
                {
                    case "ActiveDocumentChanged":
                    {
                        CopyScriptCommand.RaiseCanExecuteChanged();
                        SaveCommand.RaiseCanExecuteChanged();
                        SaveAsCommand.RaiseCanExecuteChanged();
                        CloseCommand.RaiseCanExecuteChanged();
                        CopyBlockCommand.RaiseCanExecuteChanged();
                        PasteCommand.RaiseCanExecuteChanged();
                        ReplaceColorsCommand.RaiseCanExecuteChanged();
                        ApplyThemeToScriptCommand.RaiseCanExecuteChanged();
                        EditMasterThemeCommand.RaiseCanExecuteChanged();
                        CreateThemeCommand.RaiseCanExecuteChanged();
                        RaisePropertyChanged("ActiveDocumentIsScript");
                        RaisePropertyChanged("ActiveDocumentIsTheme");
                        RaisePropertyChanged("ShowAdvancedStatus");
                        break;
                    }
                    case "NewScript":
                    {
                        OnNewScriptCommand();
                        break;
                    }
                    case "OpenScript":
                    {
#pragma warning disable 4014
                        OnOpenScriptCommand();
#pragma warning restore 4014
                        break;
                    }
                    case "ShowLoadingBanner":
                    {
                        ShowLoadingBanner = true;
                        break;
                    }
                    case "HideLoadingBanner":
                    {
                        ShowLoadingBanner = false;
                        break;
                    }
                }
            });
        }
        public void SetValueShouldUpdateIsEnabledProperty()
        {
            bool canExecute = false;
            var command = new RelayCommand(o => { }, o => canExecute, this);

            var srcAccessor = new BindingSourceAccessorMock();
            var source = new BindingSourceModel();
            var accessor = GetAccessor(source, BindingSourceModel.EventName, EmptyContext, false);
            srcAccessor.GetValue = (info, context, arg3) => command;

            accessor.SetValue(srcAccessor, EmptyContext, true);
            source.IsEnabled.ShouldBeFalse();
            canExecute = true;
            command.RaiseCanExecuteChanged();
            source.IsEnabled.ShouldBeTrue();
        }
        public void AccessorShouldUseCommandParameterCanExecuteOneTimeModeAfterDispose()
        {
            bool isInvoked = false;
            var parameter = new object();
            var command = new RelayCommand(o => { }, o =>
            {
                o.ShouldEqual(parameter);
                isInvoked = true;
                return false;
            }, this);
            var srcAccessor = new BindingSourceAccessorMock();
            var source = new BindingSourceModel();
            var ctx = new DataContext(BindingBuilderConstants.Behaviors.ToValue(new List<IBindingBehavior> { new OneTimeBindingMode() }));
            var accessor = GetAccessor(source, BindingSourceModel.EventName, ctx, false, d => parameter);
            srcAccessor.GetValue = (info, context, arg3) => command;

            accessor.SetValue(srcAccessor, EmptyContext, true);
            accessor.Dispose();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            isInvoked.ShouldBeTrue();

            isInvoked = false;
            command.RaiseCanExecuteChanged();
            isInvoked.ShouldBeTrue();
            source.ToString();//TO KEEP ALIVE
        }
        public void AccessorShouldToggleEnabledFalse()
        {
            bool canExecute = false;
            bool isInvoked = false;
            var parameter = new object();
            var command = new RelayCommand(o => { }, o =>
            {
                o.ShouldEqual(parameter);
                isInvoked = true;
                return canExecute;
            }, this);
            bool isEnabled = true;
            IAttachedBindingMemberInfo<object, bool> member =
                AttachedBindingMember.CreateMember<object, bool>(AttachedMemberConstants.Enabled,
                    (info, o) => isEnabled,
                    (info, o, v) => isEnabled = v);
            var memberProvider = new BindingMemberProvider();
            memberProvider.Register(typeof(object), member, false);
            BindingServiceProvider.MemberProvider = memberProvider;

            var srcAccessor = new BindingSourceAccessorMock();
            var source = new BindingSourceModel();
            var accessor = GetAccessor(source, BindingSourceModel.EventName, new DataContext(BindingBuilderConstants.ToggleEnabledState.ToValue(false)), false, d => parameter);
            srcAccessor.GetValue = (info, context, arg3) => command;

            isEnabled.ShouldBeTrue();
            accessor.SetValue(srcAccessor, EmptyContext, true);
            isInvoked.ShouldBeFalse();
            isEnabled.ShouldBeTrue();

            isInvoked = false;
            canExecute = true;
            command.RaiseCanExecuteChanged();
            isInvoked.ShouldBeFalse();
            isEnabled.ShouldBeTrue();
        }