public void Raise2TimesExecuteChanged() { DelegateCommand command = new DelegateCommand(() => { }); AssertHelper.CanExecuteChangedEvent(command, () => { command.RaiseCanExecuteChanged(); command.RaiseCanExecuteChanged(); }); }
public VisualizationStateViewModel( string name, ObservableCollection<object> allRecords ) { _name = name; _allRecords = allRecords; _recordsPaneVisiblity = Visibility.Collapsed; _showOrHideRecordsCommand = new DelegateCommand<object>(OnShowOrHideRecords, CanShowOrHideRecords); _exportImageCommand = new DelegateCommand<object>(OnExportImage, CanExportImage); _allRecords.CollectionChanged += (s, a) => { Action action = () => { NotifyOfPropertyChange(() => HasRecords); _showOrHideRecordsCommand.RaiseCanExecuteChanged(); }; if( null != Dispatcher && ! Dispatcher.CheckAccess() ) { Dispatcher.BeginInvoke(action, DispatcherPriority.Normal, null); } else { action(); } }; }
public InboxViewModel(IEmailService emailService, IRegionManager regionManager) { synchronizationContext = SynchronizationContext.Current ?? new SynchronizationContext(); _composeMessageCommand = new DelegateCommand<object>(ComposeMessage); _replyMessageCommand = new DelegateCommand<object>(ReplyMessage, CanReplyMessage); _openMessageCommand = new DelegateCommand<EmailDocument>(OpenMessage); messagesCollection = new ObservableCollection<EmailDocument>(); Messages = new CollectionView(this.messagesCollection); Messages.CurrentChanged += (s, e) => _replyMessageCommand.RaiseCanExecuteChanged(); _emailService = emailService; _regionManager = regionManager; if (_emailService != null) { _emailService.BeginGetEmailDocuments( r => { var messages = _emailService.EndGetEmailDocuments(r); synchronizationContext.Post( s => { foreach (var message in messages) { messagesCollection.Add(message); } }, null); }, null); } }
public void RaiseCanExecuteChangedRaisesCanExecuteChanged() { var handlers = new DelegateHandlers(); var command = new DelegateCommand<object>(handlers.Execute); bool canExecuteChangedRaised = false; command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; }; command.RaiseCanExecuteChanged(); Assert.IsTrue(canExecuteChangedRaised); }
public void Init(Model model) { InitializeComponent(); try { OnCompleted += () => { disposables.Dispose(); }; disposables.Add(Observable.FromEventPattern<MouseWheelEventArgs>(scroll, "PreviewMouseWheel") .Subscribe(evarg => { scroll.ScrollToVerticalOffset(-1 * evarg.EventArgs.Delta); }) ); listReceivers.ItemsSource = model.receivers; listReceivers.CreateBinding(ListBox.SelectedValueProperty, model, x => x.selection, (m, o) => { m.selection = o; }); var createReceiverCommand = new DelegateCommand( () => Success(new Result.Create(model)), () => true ); createReceiverButton.Command = createReceiverCommand; var deleteReceiverCommand = new DelegateCommand( () => Success(new Result.Delete(model)), () => model.selection != null ); deleteReceiverButton.Command = deleteReceiverCommand; var modifyReceiverCommand = new DelegateCommand( () => Success(new Result.Modify(model)), () => model.selection != null ); modifyReceiverButton.Command = modifyReceiverCommand; disposables.Add( model .GetPropertyChangedEvents(m => m.selection) .Subscribe(v => { modifyReceiverCommand.RaiseCanExecuteChanged(); deleteReceiverCommand.RaiseCanExecuteChanged(); }) ); } catch(Exception err) { dbg.Error(err); } }
public void CanExecuteChanged() { bool b = false; int i = 0; Action execute = (() => { }); Func<bool> predicate = (() => b); var command = new DelegateCommand(execute, predicate); EventHandler eventHandler = (sender, eventArgs) => { Assert.AreSame(command, sender); Assert.IsNotNull(eventArgs); i++; }; command.CanExecuteChanged += eventHandler; command.RaiseCanExecuteChanged(); Assert.AreEqual(1, i); command.RaiseCanExecuteChanged(); command.RaiseCanExecuteChanged(); Assert.AreEqual(3, i); command.CanExecuteChanged -= eventHandler; command.RaiseCanExecuteChanged(); Assert.AreEqual(3, i); }
public MainWindowViewModel() { _BrowseFolderCommand = new DelegateCommand(DoBrowseFolderCommand, CanDoBrowseFolderCommand); _CloseFolderCommand = new DelegateCommand(DoCloseFolderCommand, CanDoCloseFolderCommand); _GotoFirstFileCommand = new DelegateCommand(DoGotoFirstFileCommand, CanDoGotoFirstFileCommand); _GotoPreviousFileCommand = new DelegateCommand(DoGotoPreviousFileCommand, CanDoGotoPreviousFileCommand); _GotoNextFileCommand = new DelegateCommand(DoGotoNextFileCommand, CanDoGotoNextFileCommand); _GotoLastFileCommand = new DelegateCommand(DoGotoLastFileCommand, CanDoGotoLastFileCommand); _GotoImageNameCommand = new DelegateCommand(DoGotoImageNameCommand, CanDoGotoImageNameCommand); _ZoomInCommand = new DelegateCommand(DoZoomInCommand, CanDoZoomInCommandCommand); _ZoomOutCommand = new DelegateCommand(DoZoomOutCommand, CanDoZoomOutCommandCommand); _ActualSizeCommand = new DelegateCommand(DoActualSizeCommand, CanDoActualSizeCommandCommand); _ZoomFitCommand = new DelegateCommand(DoZoomFitCommand, CanDoZoomFitCommandCommand); _FitWidthCommand = new DelegateCommand(DoFitWidthCommand, CanDoFitWidthCommandCommand); _FitHeightCommand = new DelegateCommand(DoFitHeightCommand, CanDoFitHeightCommandCommand); _RenameActiveImageCommand = new DelegateCommand(DoRenameActiveImageCommand, CanDoRenameActiveImageCommand); _DeleteActiveImageCommand = new DelegateCommand(DoDeleteActiveImageCommand, CanDoDeleteActiveImageCommand); _RefreshActiveImageCommand = new DelegateCommand(DoRefreshActiveImageCommand, CanDoRefreshActiveImageCommandCommand); _AboutCommand = new DelegateCommand(DoAboutCommand, CanDoAboutCommand); _ActiveImagesViewModel = new ActiveImagesViewModel(); _ActiveImagesViewModel.ActiveFilesCollection.CollectionChanged += (s, e) => { _CloseFolderCommand.RaiseCanExecuteChanged(); RaisePositionCommandEvents(); RaiseZoomCommandEvents(); RaiseFileOperationEvents(); }; _ActiveImagesViewModel.ActiveImageChanged += (s, e) => { RaisePositionCommandEvents(); }; _ActiveImagesViewModel.PropertyChanged += (s, e) => { switch (e.PropertyName) { case "IsLoadingFiles": RaiseFileOperationEvents(); break; } }; }
//TODO: Inject a Func<IGoogleLoginView> instead public GoogleProvider(IAuthorizationModel authorizationModel, IRegionManager regionManager, IGoogleLoginView loginView, ILoggerFactory loggerFactory) { _authorizationModel = authorizationModel; _regionManager = regionManager; _loginView = loginView; _logger = loggerFactory.GetLogger(); _logger.Debug("GoogleProvider.ctor(...)"); _regionManager.Regions["WindowRegion"].Add(_loginView); _authorizationModel.RegisterAuthorizationCallback(ShowGoogleLogin); _authorizeCommand = new DelegateCommand(RequestAuthorization, () => !Status.IsAuthorized && !Status.IsProcessing); _authorizationModel.Status.Subscribe(_ => { OnPropertyChanged("Status"); _authorizeCommand.RaiseCanExecuteChanged(); }); }
public ResizeCommandsViewModel(IResizeViewModel resizeViewModel, IResizeService resizeService) { if(resizeViewModel == null) throw new ArgumentNullException("resizeViewModel"); if(resizeService == null) throw new ArgumentNullException("resizeService"); this.resizeViewModel = resizeViewModel; this.resizeService = resizeService; resizeFileCommand = new DelegateCommand(Resize, CanResize); resizeFolderCommand = new DelegateCommand(ResizeFolder, CanResize); Observable.FromEventPattern<PropertyChangedEventArgs>(this.resizeViewModel, "PropertyChanged") .Subscribe(x => { resizeFileCommand.RaiseCanExecuteChanged(); resizeFolderCommand.RaiseCanExecuteChanged(); }); }
public void CanRemoveCanExecuteChangedHandler() { var command = new DelegateCommand<object>((o) => { }); bool canExecuteChangedRaised = false; EventHandler handler = (s, e) => canExecuteChangedRaised = true; command.CanExecuteChanged += handler; command.CanExecuteChanged -= handler; command.RaiseCanExecuteChanged(); Assert.IsFalse(canExecuteChangedRaised); }
void OnLoggedIn(dynamic result) { if (result["Result"].ToObject<bool>()) { m_FieldMetadatas = result["FieldMetadatas"].ToObject<StateFieldMetadata[]>(); var nodeInfo = DynamicViewModelFactory.Create(result["NodeInfo"].ToString()); BuildGridColumns(m_FieldMetadatas); GlobalInfo = nodeInfo.GlobalInfo; var instances = nodeInfo.Instances as IEnumerable<DynamicViewModel.DynamicViewModel>; Instances = new ObservableCollection<DynamicViewModel.DynamicViewModel>(instances.Select(i => { var startCommand = new DelegateCommand<DynamicViewModel.DynamicViewModel>(ExecuteStartCommand, CanExecuteStartCommand); var stopCommand = new DelegateCommand<DynamicViewModel.DynamicViewModel>(ExecuteStopCommand, CanExecuteStopCommand); i.PropertyChanged += (s, e) => { if (string.IsNullOrEmpty(e.PropertyName) || e.PropertyName.Equals("IsRunning", StringComparison.OrdinalIgnoreCase)) { startCommand.RaiseCanExecuteChanged(); stopCommand.RaiseCanExecuteChanged(); } }; i.Set("StartCommand", startCommand); i.Set("StopCommand", stopCommand); return i; })); State = NodeState.Connected; LastUpdatedTime = DateTime.Now; } else { m_LoginFailed = true; //login failed m_WebSocket.Close(); ErrorMessage = "Logged in failed!"; } }
public void Precondition_Command_Null() { DelegateCommand command = new DelegateCommand(() => { }); AssertHelper.CanExecuteChangedEvent(null, () => command.RaiseCanExecuteChanged()); }
public void CommandCanExecuteChangedTest() { DelegateCommand command = new DelegateCommand(() => { }); AssertHelper.CanExecuteChangedEvent(command, () => command.RaiseCanExecuteChanged()); }
public void Init(Model model) { InitializeComponent(); OnCompleted += () => { disposables.Dispose(); }; var availableActions = new ObservableCollection<Action1>(); var includedActions = new ObservableCollection<Action1>(); var applyCommand = new DelegateCommand( () => { model.trigger.Configuration.TopicExpression = GetTopicExression(); if (string.IsNullOrEmpty(model.trigger.Configuration.TopicExpression.Any.First().InnerText)) model.trigger.Configuration.TopicExpression = null; if (string.IsNullOrEmpty(model.trigger.Configuration.ContentExpression.Any.First().InnerText)) model.trigger.Configuration.ContentExpression = null; model.trigger.Configuration.ActionToken = includedActions.Select(a => a.Token).ToArray(); Success(new Result.Apply(model)); }, () => true ); applyButton.Command = applyCommand; var cancelCommand = new DelegateCommand( () => Success(new Result.Cancel(model)), () => true ); cancelButton.Command = cancelCommand; FixModel(model); { // token valueToken.CreateBinding(TextBlock.TextProperty, model.trigger, x => x.Token); if (string.IsNullOrEmpty(model.trigger.Token)) { captionToken.Visibility = Visibility.Collapsed; valueToken.Visibility = Visibility.Collapsed; } } { // topic filter var concreteSetTopics = GetConcreteSetTopics(model.topicSet); concreteSetTopics.Insert(0, string.Empty); var topicExpr = model.trigger.Configuration.TopicExpression.Any.First().InnerText; var topicExprParts = topicExpr.Split(new char[] { '|' }); foreach (var part in topicExprParts) { var control = CreateTopicExprControl(concreteSetTopics, part); valuesTopicExpr.Items.Add(control); } var addTopicExprPartCommand = new DelegateCommand( executeMethod: () => { var control = CreateTopicExprControl(concreteSetTopics, string.Empty); valuesTopicExpr.Items.Add(control); }, canExecuteMethod: () => valuesTopicExpr.Items.Count <= 32 ); addTopicExprPartButton.Command = addTopicExprPartCommand; } { // content filter valueContentExpr.CreateBinding(TextBox.TextProperty, model.trigger.Configuration.ContentExpression , m => m.Any.First().InnerText , (m, v) => m.Any = new XmlNode[] { new XmlDocument().CreateTextNode(v) }); } { // actions var addActionCommand = new DelegateCommand( () => { var actions = (listAvailableActions.SelectedItems ?? new ArrayList()).Select(i => (Action1)i).ToList(); availableActions.RemoveRange(actions); includedActions.AddRange(actions); }, () => (listAvailableActions.SelectedItems ?? new ArrayList()).Count > 0 ); addActionButton.Command = addActionCommand; var removeActionCommand = new DelegateCommand( () => { var actions = (listIncludedActions.SelectedItems ?? new ArrayList()).Select(i => (Action1)i).ToList(); includedActions.RemoveRange(actions); availableActions.AddRange(actions); }, () => (listIncludedActions.SelectedItems ?? new ArrayList()).Count > 0 ); removeActionButton.Command = removeActionCommand; includedActions.AddRange(model.trigger.Configuration.ActionToken.Select(token => model.actions.First(a => a.Token == token)).ToList()); availableActions.AddRange(model.actions.Except(includedActions).ToList()); listAvailableActions.ItemsSource = availableActions; listIncludedActions.ItemsSource = includedActions; listIncludedActions.SelectionChanged += delegate { removeActionCommand.RaiseCanExecuteChanged(); }; listAvailableActions.SelectionChanged += delegate { addActionCommand.RaiseCanExecuteChanged(); }; } Localization(); }
public CustomerListViewModel(IUnityContainer container, IRegionManager regionManager, IEventAggregator eventAggregator) { _container = container; _eventAggregator = eventAggregator; _regionManager = regionManager; _clientLayer = new ClientLayer(); _customers = new ObservableCollection<Customer>(); _collectionView = new ListCollectionView(_customers); _editCustomerDetailsCommand = new DelegateCommand<bool?>(this.ExecuteEditCustomerDetails, this.CanExecuteEditCustomerDetails); _сreateCustomerCommand = new DelegateCommand<Customer>(this.CreateCustomer); _collectionView.CurrentChanged += (s, e) => _editCustomerDetailsCommand.RaiseCanExecuteChanged(); _collectionView.CurrentChanged += new EventHandler(this.SelectedCustomerChanged); IEnumerable<Customer> newCustomers = _clientLayer.GetAllCustomers(); foreach (var item in newCustomers) { _customers.Add(item); } }
public void ShouldReraiseDelegateCommandCanExecuteChangedEventAfterCollect() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); DelegateCommand<object> delegateCommand = new DelegateCommand<object>(delegate { }); Assert.False(multiCommand.CanExecuteChangedRaised); multiCommand.RegisterCommand(delegateCommand); multiCommand.CanExecuteChangedRaised = false; GC.Collect(); delegateCommand.RaiseCanExecuteChanged(); Assert.True(multiCommand.CanExecuteChangedRaised); }
private void InitializeBar2Command(DelegateCommand<String> command) { PropertyChangedInternal += (sender, args) => { if (args.PropertyName == "BarParameter") command.RaiseCanExecuteChanged (); }; }
public void ShouldRemoveCanExecuteChangedHandler() { bool canExecuteChangedRaised = false; var compositeCommand = new CompositeCommand(); var commmand = new DelegateCommand(() => { }); compositeCommand.RegisterCommand(commmand); EventHandler handler = (s, e) => canExecuteChangedRaised = true; compositeCommand.CanExecuteChanged += handler; commmand.RaiseCanExecuteChanged(); Assert.True(canExecuteChangedRaised); canExecuteChangedRaised = false; compositeCommand.CanExecuteChanged -= handler; commmand.RaiseCanExecuteChanged(); Assert.False(canExecuteChangedRaised); }
public void ShouldKeepWeakReferenceToOnCanExecuteChangedHandlers() { var command = new DelegateCommand<MyClass>((MyClass c) => { }); var handlers = new CanExecutChangeHandler(); var weakHandlerRef = new WeakReference(handlers); command.CanExecuteChanged += handlers.CanExecuteChangeHandler; handlers = null; GC.Collect(); command.RaiseCanExecuteChanged(); Assert.IsFalse(weakHandlerRef.IsAlive); }
public void UpdateIsEnabledOnCanExecuteChanged() { bool canExecute = true; bool executed = false; var command = new DelegateCommand<string>(o => executed = true, o => canExecute); using(var button = new Button()) { button.SetCommand(command); Assert.That(button.Enabled, Is.True); canExecute = false; Assert.That(button.Enabled, Is.True); button.PerformClick(); Assert.That(executed, Is.False); Assert.That(button.Enabled, Is.True); TestUtils.GarbageCollect(); command.RaiseCanExecuteChanged(); Assert.That(button.Enabled, Is.False); Assert.That(command.CanExecuteChangedSubscribeCount, Is.EqualTo(1)); WeakReference handlerRef = GetHandlerRef(button); button.SetCommand(null); Assert.That(command.CanExecuteChangedSubscribeCount, Is.EqualTo(0)); TestUtils.GarbageCollect(); Assert.That(handlerRef.IsAlive, Is.False); } }
public void ShouldKeepWeakReferenceToOnCanExecuteChangedHandlers() { var command = new DelegateCommand<MyClass>((MyClass c) => { }); var handlers = new CanExecutChangeHandler(); var weakHandlerRef = new WeakReference(handlers); command.CanExecuteChanged += handlers.CanExecuteChangeHandler; handlers = null; GC.Collect(); command.RaiseCanExecuteChanged(); Assert.IsFalse(weakHandlerRef.IsAlive); Assert.IsNotNull(command); // Only here to ensure command survives optimizations and the GC.Collect }
public void CanExecuteChangedEventShouldBeWeak() { bool b = false; Action execute = (() => { }); Func<bool> predicate = (() => b); var command = new DelegateCommand(execute, predicate); command.CanExecuteChanged += new EventConsumer().EventHandler; // Garbage collect the EventConsumer. GC.Collect(); EventConsumer.Clear(); command.RaiseCanExecuteChanged(); Assert.IsFalse(EventConsumer.EventCalled); }
public MainViewModel(IDialogCoordinator _dialogCoordinator) { DialogCoordinator = _dialogCoordinator; try { NativeMethods.EnablePrivilege("SeBackupPrivilege"); NativeMethods.EnablePrivilege("SeRestorePrivilege"); IsAdmin = true; } catch { } ActiveView = this; var computer = new RegistryKeyItemSpecial(null) { Text = "Computer", Icon = "/images/workstation2.png", IsExpanded = true }; computer.SubItems.Add(new RegistryKeyItem(computer, Registry.ClassesRoot)); computer.SubItems.Add(new RegistryKeyItem(computer, Registry.CurrentUser)); computer.SubItems.Add(new RegistryKeyItem(computer, Registry.LocalMachine)); computer.SubItems.Add(new RegistryKeyItem(computer, Registry.CurrentConfig)); computer.SubItems.Add(new RegistryKeyItem(computer, Registry.Users)); _roots = new List<RegistryKeyItemBase> { computer, //new RegistryKeyItemSpecial(null) { // Text = "Files", // Icon = "/images/folder_blue.png" //}, new RegistryKeyItemSpecial(null) { Text = "Favorites", Icon = "/images/favorites.png", IsExpanded = true } }; LoadFavorites(); ExitCommand = new DelegateCommand(() => Application.Current.Shutdown()); LaunchWithAdminRightsCommand = new DelegateCommand(() => { var pi = new ProcessStartInfo(Process.GetCurrentProcess().MainModule.FileName) { Verb = "RunAs" }; try { if(Process.Start(pi) != null) { Environment.Exit(0); } } catch(Exception ex) { MessageBox.Show(ex.Message, App.Name); } }, () => !IsAdmin); EditNewKeyCommand = new DelegateCommand<RegistryKeyItem>(item => { var name = item.GenerateUniqueSubKeyName(); CommandManager.AddCommand(Commands.CreateKey(new CreateKeyCommandContext { Key = item, Name = name })); item.IsExpanded = true; var newItem = item.GetSubItem<RegistryKeyItem>(name); newItem.IsSelected = true; Dispatcher.CurrentDispatcher.InvokeAsync(() => IsEditMode = true, DispatcherPriority.Background); }, item => !IsReadOnlyMode && item is RegistryKeyItem) .ObservesProperty(() => IsReadOnlyMode); EditPermissionsCommand = new DelegateCommand(() => { // TODO }, () => SelectedItem is RegistryKeyItem) .ObservesProperty(() => SelectedItem); CopyKeyNameCommand = new DelegateCommand<RegistryKeyItemBase>(_ => Clipboard.SetText(SelectedItem.Text), _ => SelectedItem != null).ObservesProperty(() => SelectedItem); CopyKeyPathCommand = new DelegateCommand(() => Clipboard.SetText(((RegistryKeyItem)SelectedItem).Path ?? SelectedItem.Text), () => SelectedItem is RegistryKeyItem) .ObservesProperty(() => SelectedItem); RefreshCommand = new DelegateCommand(() => SelectedItem.Refresh(), () => SelectedItem != null) .ObservesProperty(() => SelectedItem); EndEditingCommand = new DelegateCommand<string>(async name => { try { var item = SelectedItem as RegistryKeyItem; Debug.Assert(item != null); if(name == null || name.Equals(item.Text, StringComparison.InvariantCultureIgnoreCase)) return; if(item.Parent.SubItems.Any(i => name.Equals(i.Text, StringComparison.InvariantCultureIgnoreCase))) { await DialogCoordinator.ShowMessageAsync(this, App.Name, string.Format("Key name '{0}' already exists", name)); return; } CommandManager.AddCommand(Commands.RenameKey(new RenameKeyCommandContext { Key = item, OldName = item.Text, NewName = name })); } catch(Exception ex) { MessageBox.Show(ex.Message, App.Name); } finally { IsEditMode = false; CommandManager.UpdateChanges(); UndoCommand.RaiseCanExecuteChanged(); RedoCommand.RaiseCanExecuteChanged(); } }, _ => IsEditMode).ObservesCanExecute(_ => IsEditMode); BeginRenameCommand = new DelegateCommand(() => IsEditMode = true, () => !IsReadOnlyMode && SelectedItem is RegistryKeyItem && !string.IsNullOrEmpty(((RegistryKeyItem)SelectedItem).Path)) .ObservesProperty(() => SelectedItem).ObservesProperty(() => IsReadOnlyMode); UndoCommand = new DelegateCommand(() => { CommandManager.Undo(); RedoCommand.RaiseCanExecuteChanged(); UndoCommand.RaiseCanExecuteChanged(); }, () => !IsReadOnlyMode && CommandManager.CanUndo).ObservesProperty(() => IsReadOnlyMode); RedoCommand = new DelegateCommand(() => { CommandManager.Redo(); UndoCommand.RaiseCanExecuteChanged(); RedoCommand.RaiseCanExecuteChanged(); }, () => !IsReadOnlyMode && CommandManager.CanRedo).ObservesProperty(() => IsReadOnlyMode); LoadHiveCommand = new DelegateCommand(async () => { var vm = DialogHelper.ShowDialog<LoadHiveViewModel, LoadHiveView>(); if(vm.ShowDialog() == true) { int error = NativeMethods.RegLoadKey(vm.Hive == "HKLM" ? Registry.LocalMachine.Handle : Registry.Users.Handle, vm.Name, vm.FileName); if(error != 0) { await DialogCoordinator.ShowMessageAsync(this, App.Name, string.Format("Error opening file: {0}", error.ToString())); return; } var item = _roots[0].SubItems[vm.Hive == "HKLM" ? 2 : 4]; item.Refresh(); ((RegistryKeyItem)item.SubItems.First(i => i.Text == vm.Name)).HiveKey = true; } }, () => IsAdmin && !IsReadOnlyMode) .ObservesProperty(() => IsReadOnlyMode); DeleteCommand = new DelegateCommand(() => { var item = SelectedItem as RegistryKeyItem; Debug.Assert(item != null); if(!IsAdmin) { if(MessageBox.Show("Running with standard user rights prevents undo for deletion. Delete anyway?", App.Name, MessageBoxButton.OKCancel, MessageBoxImage.Exclamation) == MessageBoxResult.Cancel) return; CommandManager.Clear(); } var tempFile = Path.GetTempFileName(); CommandManager.AddCommand(Commands.DeleteKey(new DeleteKeyCommandContext { Key = item, TempFile = tempFile })); CommandManager.UpdateChanges(); UndoCommand.RaiseCanExecuteChanged(); RedoCommand.RaiseCanExecuteChanged(); }, () => !IsReadOnlyMode && SelectedItem is RegistryKeyItem && SelectedItem.Path != null).ObservesProperty(() => IsReadOnlyMode); ExportCommand = new DelegateCommand(() => { var dlg = new SaveFileDialog { Title = "Select output file", Filter = "Registry data files|*.dat", OverwritePrompt = true }; if(dlg.ShowDialog() == true) { var item = SelectedItem as RegistryKeyItem; Debug.Assert(item != null); using(var key = item.Root.OpenSubKey(item.Path)) { File.Delete(dlg.FileName); int error = NativeMethods.RegSaveKeyEx(key.Handle, dlg.FileName, IntPtr.Zero, 2); Debug.Assert(error == 0); } } }, () => IsAdmin && SelectedItem is RegistryKeyItem) .ObservesProperty(() => SelectedItem); CreateNewValueCommand = new DelegateCommand<ValueViewModel>(vm => { }, vm => !IsReadOnlyMode) .ObservesProperty(() => IsReadOnlyMode); AddToFavoritesCommand = new DelegateCommand(() => { var item = SelectedItem as RegistryKeyItem; Debug.Assert(item != null); _roots[1].SubItems.Add(new RegistryKeyItem(item.Parent as RegistryKeyItem, item.Text)); SaveFavorites(); }, () => SelectedItem is RegistryKeyItem && !string.IsNullOrEmpty(SelectedItem.Path)) .ObservesProperty(() => SelectedItem); RemoveFromFavoritesCommand = new DelegateCommand(() => { _roots[1].SubItems.Remove(SelectedItem); SaveFavorites(); }, () => SelectedItem != null && SelectedItem.Flags.HasFlag(RegistryKeyFlags.Favorite)) .ObservesProperty(() => SelectedItem); }