public SimpleGraphViewModel()
        {
            var observer = MementoObserver.Monitor(service);

            UndoCommand = DelegateCommand.Create()
                          .OnCanExecute(o => service.CanUndo)
                          .OnExecute(o => service.Undo())
                          .AddMonitor(observer);

            RedoCommand = DelegateCommand.Create()
                          .OnCanExecute(o => service.CanRedo)
                          .OnExecute(o => service.Redo())
                          .AddMonitor(observer);

            var person = new Person()
            {
                FirstName = "Mauro",
                LastName  = "Servienti"
            };

            var entity = new PersonViewModel();

            service.Attach(entity);

            entity.Initialize(person, false);

            Entity = entity;
        }
 public WarehouseViewModel(WarehouseView owner)
 {
     this.owner      = owner;
     Warehouses      = new ObservableCollection <Warehouse>();
     AddCommand      = DelegateCommand.Create(Add);
     ToDetailCommand = DelegateCommand.Create(owner.ToDetail);
 }
Example #3
0
        /// <summary>
        /// This basic implementation just sets a binding on the targeted
        /// <see cref="DependencyObject"/> and returns the appropriate
        /// <see cref="BindingExpressionBase"/> instance.<br/>
        /// All this work is delegated to the decorated <see cref="Binding"/>
        /// instance.
        /// </summary>
        /// <param name="provider">Object that can provide services for the markup
        /// extension.</param>
        /// <returns>
        /// The object value to set on the property where the extension is applied.
        /// In case of a valid binding expression, this is a <see cref="BindingExpressionBase"/>
        /// instance.
        /// </returns>
        public override object ProvideValue(IServiceProvider provider)
        {
            /*
             * We basically have a problem here, since we cannot
             * create the "runtime" delagate command until the target
             * object is loaded if we return the base provided value,
             * that is a "Binding" object the binding is runtime evaluated
             * and null is returned because obviously the Path does not exists
             * on the source object.
             *
             * So if the base CommandBinding returns itself it means the we are
             * currently using a Shared Dependency Property so we need to delay the
             * resolution; otherwise we return a fake empty command just to let the
             * Wpf binding engine to belive everything is working fine and wait for
             * the target to be loaded.
             */
            //var value = base.ProvideValue( provider );
            //if( Object.Equals( value, this ) )
            //{
            //    return this;
            //}

            base.ProvideValue(provider);

            if (this.IsUsingSharedDependencyProperty(provider))
            {
                return(this);
            }

            var fakePlaceholder = DelegateCommand.Create();

            return(fakePlaceholder);
        }
        public MainPageViewModel(IWorkerServiceClientFactory factory)
        {
            this.factory = factory;

            this.ExecuteEcho = DelegateCommand.Create()
                               .OnExecute(o =>
            {
                var context = TaskScheduler.FromCurrentSynchronizationContext();
                using (var client = this.factory.CreateAsyncClient())
                {
                    client.WorkOnAsync(new Job(new EchoJobTask()
                    {
                        Message = this.Message
                    }))
                    .ContinueWith(e =>
                    {
                        var r           = e.Result.GetTaskResult <EchoJobTaskResult>().EchoedMessage;
                        this.EchoResult = r;
                    }, context);
                }

                using (var client = this.factory.CreateAsyncClient())
                {
                    client.ExecuteAsync(new SampleCommand())
                    .ContinueWith(e =>
                    {
                        var r = e.Result as EmptyCommandExecutionResult;
                    }, context);
                }
            });
        }
Example #5
0
        public TabControlRegionViewModel(IViewResolver viewResolver, IRegionService regionService)
        {
            AddNewGammaViewCommand =
                DelegateCommand.Create()
                .OnExecute(x =>
            {
                var view = viewResolver.GetView <GammaView>();
                if (view != null)
                {
                    regionService.GetKnownRegionManager <TabControlRegionView>()
                    .GetRegion <ISwitchingElementsRegion>("MainTabRegion")
                    .Add(view);
                }
            });

            ActivateGammaViewCommand =
                DelegateCommand.Create()
                .OnExecute(x =>
            {
                var region = regionService.GetKnownRegionManager <TabControlRegionView>()
                             .GetRegion <ISwitchingElementsRegion>("MainTabRegion");

                var elements = region.GetElements <DependencyObject>()
                               .OfType <GammaView>()
                               .Cast <DependencyObject>()
                               .ToList();

                if (elements.Count > 0)
                {
                    var index = elements.IndexOf(region.ActiveContent);
                    if (index >= 0)
                    {
                        DependencyObject viewToActivate = index + 1 < elements.Count
                                                                                 ? elements[index + 1]
                                                                                 : elements[0];

                        region.Activate(viewToActivate);
                    }
                    else
                    {
                        region.Activate(elements[0]);
                    }
                }
            });

            RemoveLastViewCommand =
                DelegateCommand.Create()
                .OnExecute(x =>
            {
                var region = regionService.GetKnownRegionManager <TabControlRegionView>()
                             .GetRegion <ISwitchingElementsRegion>("MainTabRegion");

                var lastElement = region.GetElements <DependencyObject>().LastOrDefault();
                if (lastElement != null)
                {
                    region.Remove(lastElement);
                }
            });
        }
Example #6
0
 public ViewModel()
 {
     CreateSerializer();
     HtmlPage.RegisterScriptableObject("eventViewerViewModel", this);
     Events        = new ObservableCollection <IEvent>();
     ReloadCommand = DelegateCommand.Create(Reload);
     Load();
 }
 public ItemViewModel(ItemView owner)
 {
     this.owner    = owner;
     Items         = new ObservableCollection <Item>();
     UpdateCommand = DelegateCommand.Create(Update);
     ResetCommand  = DelegateCommand.Create(o => InitAsync());
     DeleteCommand = DelegateCommand.Create(Delete);
 }
 public CustomerViewModel(CustomerView owner)
 {
     this.owner    = owner;
     Customers     = new ObservableCollection <Customer>();
     UpdateCommand = DelegateCommand.Create(Update);
     ResetCommand  = DelegateCommand.Create(o => InitAsync());
     DeleteCommand = DelegateCommand.Create(Delete);
     ToDealCommand = DelegateCommand.Create(owner.ToDeal);
 }
        public ShellStartScreenViewModel(IMessageBroker messageBroker)
        {
            Debug.WriteLine("ShellStartScreenViewModel()");

            this.messageBroker = messageBroker;

            this.OpenView = DelegateCommand.Create()
                            .OnExecute(OpenViewHandler);
        }
        public CompositeAppViewModel(IMessageBroker messageBroker)
        {
            Debug.WriteLine("CompositeAppViewModel()");

            this.messageBroker = messageBroker;

            this.OpenStartScreen = DelegateCommand.Create()
                                   .OnExecute(p => OpenStartScreenHandler());
        }
Example #11
0
 public SalemanViewModel(SalemanView owner)
 {
     this.owner    = owner;
     Salemen       = new ObservableCollection <Salesman>();
     UpdateCommand = DelegateCommand.Create(Update);
     ResetCommand  = DelegateCommand.Create(o => InitAsync());
     DeleteCommand = DelegateCommand.Create(Delete);
     ToDealCommand = DelegateCommand.Create(owner.ToDeal);
 }
        public TransferViewModel(IMessenger messenger, IAccountsOverview accountsOverview)
        {
            _messenger = messenger;
            Amount     = "0";
            messenger.SubscribeTo <TransferMessage>(t =>
            {
                From   = t.AccountNumber;
                To     = string.Empty;
                Amount = "0";
            });
            _accountsOverview = accountsOverview;

            TransferCommand = DelegateCommand.Create(Transfer);
        }
        public void delegateCommand_trigger_using_mementoMonitor_and_manually_calling_notifyChanged_should_raise_CanExecuteChanged()
        {
            var expected = 1;
            var actual   = 0;

            var svc     = MockRepository.GenerateStub <IChangeTrackingService>();
            var monitor = new MementoMonitor(svc);

            var target = DelegateCommand.Create().AddMonitor(monitor);

            target.CanExecuteChanged += (s, e) => actual++;
            monitor.NotifyChanged();

            actual.Should().Be.EqualTo(expected);
        }
        public void delegateCommand_trigger_using_PropertyObserver_ForAllproperties_should_trigger_canExecuteChanged()
        {
            var expected = 2;
            var actual   = 0;

            var stub = new TestStub();

            var target = DelegateCommand.Create().Observe(stub);

            target.CanExecuteChanged += (s, e) => actual++;

            stub.Value        = "this raises PropertyChanged";
            stub.AnotherValue = "this raises PropertyChanged";

            actual.Should().Be.EqualTo(expected);
        }
 /// <summary>
 /// Internally exposed constructor for Unit Testing
 /// </summary>
 internal HomePageViewModel(
     IFolderBrowserDialogWrapper folderBrowserDialog,
     IScannedFileStore scannedFileStore,
     string userAppDataPath) : base(scannedFileStore, userAppDataPath)
 {
     _folderBrowserDialog = folderBrowserDialog;
     _userAppDataPath     = userAppDataPath;
     this.Locations       = new ObservableCollection <ScanLocation>();
     _add            = DelegateCommand.Create(AddLocation);
     _remove         = DelegateCommand.Create(RemoveLocation, false);
     _scan           = DelegateCommand.Create(ShowScanPage, false);
     this.Add        = _add;
     this.Remove     = _remove;
     this.Scan       = _scan;
     this.PageLoaded = AsyncCommand.Create(OnPageLoaded);
 }
        public void delegateCommand_trigger_using_mementoMonitor_and_triggering_changes_on_the_memento_should_raise_canExecuteChanged()
        {
            var expected = 1;
            var actual   = 0;

            var svc     = MockRepository.GenerateStub <IChangeTrackingService>();
            var raiser  = svc.GetEventRaiser(obj => obj.TrackingServiceStateChanged += null);
            var monitor = new MementoMonitor(svc);

            var target = DelegateCommand.Create().AddMonitor(monitor);

            target.CanExecuteChanged += (s, e) => actual++;

            raiser.Raise(svc, EventArgs.Empty);

            actual.Should().Be.EqualTo(expected);
        }
Example #17
0
        public OverviewViewModel(IMessenger messenger, IAccountsOverview accountsOverview)
        {
            _messenger = messenger;
            Accounts   = accountsOverview.GetAccountsOverview();

            accountsOverview.OnAccountBalanceChanged((accountNumber, balance) =>
            {
                foreach (var accountOverview in Accounts)
                {
                    if (accountOverview.AccountNumber == accountNumber)
                    {
                        accountOverview.Balance = balance;
                    }
                }
            });

            TransferCommand = DelegateCommand.Create <string>(Transfer);
        }
Example #18
0
        public void DelegateCommand_Create()
        {
            var                 callCount  = 0;
            Action <string>     execute    = p => callCount++;
            Func <string, bool> canExecute = p => true;

            var x = DelegateCommand.Create(execute, canExecute);

            Assert.AreEqual(true, x.CanExecute(""));
            x.Execute("");
            Assert.AreEqual(1, callCount);

            var y = (ICommand)x;

            Assert.AreEqual(true, y.CanExecute(""));
            y.Execute("");
            Assert.AreEqual(2, callCount);
        }
Example #19
0
        public override void Handle(object sender, ViewLoaded message)
        {
            if (this.RegionService.HoldsRegionManager(message.View))
            {
                var manager = this.RegionService.GetRegionManager(message.View);

                var registryMenu = new MenuItem();
                registryMenu.Header = "Registry";
                registryMenu.Items.Add(new MenuItem()
                {
                    Header  = "Create...",
                    Command = DelegateCommand.Create()
                              .OnExecute(o =>
                    {
                        this.Broker.Broadcast(this, new Messaging.CreateNewCompany());
                    })
                });

                manager.GetRegion <IElementsRegion>("MainMenuRegion").Add(registryMenu);
            }
        }
        internal ResultPageViewModel(
            ILogger logger,
            IProcess process,
            IRecycleFile recycleFile,
            string userAppDataPath,
            IScannedFileStore scannedFileStore) : base(scannedFileStore, userAppDataPath)
        {
            _logger          = logger;
            _process         = process;
            _recycle         = AsyncCommand.Create(() => RecycleSelectionAsync());
            _preview         = AsyncCommand.Create(() => PreviewSelectionAsync(), false);
            _recycleFile     = recycleFile;
            _userAppDataPath = userAppDataPath;

            Duplicates                  = new ObservableCollection <ScanResult>();
            DuplicatesViewSource        = new CollectionViewSource();
            DuplicatesViewSource.Source = Duplicates;
            PageLoaded                  = AsyncCommand.Create(() => PageLoadedAsync());
            Recycle = _recycle;
            Preview = _preview;
            SelectedItemsChangedCommand = DelegateCommand.Create(ToggleButtons);
        }
Example #21
0
        public virtual IDelegateCommand CreateCommand(CommandData commandData)
        {
            var text = (commandData.Description == null) ?
                       String.Empty :
                       commandData.Description.DisplayText;

            var command = ( DelegateCommand )DelegateCommand.Create(text);

            command.SetData(commandData);

            command.OnCanExecute(o =>
            {
                var data = command.GetData <CommandData>();
                if (data.Fact != null)
                {
                    return(data.Fact.Eval(o));
                }
                else if (data.BooleanFact != null)
                {
                    var can = data.BooleanFact.FastGetter();
                    return(can);
                }

                return(true);
            })
            .OnExecute(o =>
            {
                var data = command.GetData <CommandData>();
                if (data.HasParameter)
                {
                    var prm = o;
                    if (o is IConvertible)
                    {
                        prm = Convert.ChangeType(o, data.ParameterType);
                    }

                    data.FastDelegate(data.DataContext, new[] { prm });
                }
                else
                {
                    data.FastDelegate(data.DataContext, null);
                }
            });

            if (commandData.KeyBindings != null)
            {
                commandData.KeyBindings
                .ForEach(kb => command.AddKeyGesture(kb.Key, kb.Modifiers));
            }

            IMonitor monitor = null;

            if (commandData.Fact != null)
            {
                monitor = commandData.Fact;
            }
            else if (commandData.BooleanFact != null)
            {
                monitor = PropertyObserver.For(( INotifyPropertyChanged )commandData.DataContext)
                          .Observe(commandData.BooleanFact.Name);
            }

            if (command != null && monitor != null)
            {
                command.AddMonitor(monitor);
                commandData.Monitor = monitor;
            }

            return(command);
        }
Example #22
0
 public LoginViewModel(LoginView owner)
 {
     this.owner   = owner;
     LoginCommand = DelegateCommand.Create(OnLogin);
 }
Example #23
0
        public ComplexGraphViewModel()
        {
            var observer = MementoObserver.Monitor(this.service);

            this.UndoCommand = DelegateCommand.Create()
                               .OnCanExecute(o => this.service.CanUndo)
                               .OnExecute(o => this.service.Undo())
                               .AddMonitor(observer);

            this.RedoCommand = DelegateCommand.Create()
                               .OnCanExecute(o => this.service.CanRedo)
                               .OnExecute(o => this.service.Redo())
                               .AddMonitor(observer);

            this.CreateNewAddressCommand = DelegateCommand.Create()
                                           .OnExecute(o =>
            {
                var address          = this.Entity.Addresses.AddNew();
                this.SelectedAddress = address;
            });

            this.DeleteAddressCommand = DelegateCommand.Create()
                                        .OnCanExecute(o => this.SelectedAddress != null)
                                        .OnExecute(o =>
            {
                this.SelectedAddress.Delete();
                this.SelectedAddress = this.Entity.Addresses.FirstOrDefault();
            })
                                        .AddMonitor
                                        (
                PropertyObserver.For(this)
                .Observe(v => v.SelectedAddress)
                                        );

            var person = new Person()
            {
                FirstName = "Mauro",
                LastName  = "Servienti"
            };

            person.Addresses.Add(new Address(person)
            {
                City    = "Treviglio",
                Number  = "11",
                Street  = "Where I live",
                ZipCode = "20100"
            });

            person.Addresses.Add(new Address(person)
            {
                City    = "Daolasa",
                Number  = "2",
                Street  = "Pierino",
                ZipCode = "20100"
            });

            var entity = new PersonViewModel();

            entity.Initialize(person, false);

            this.service.Attach(entity);

            this.Entity = entity;
        }
        public CustomPropertyMappingViewModel()
        {
            var data = new List <Person>()
            {
                new Person("topics")
                {
                    FirstName = "Mauro",
                    LastName  = "Servienti"
                },

                new Person("gioffy")
                {
                    FirstName = "Giorgio",
                    LastName  = "Formica"
                },

                new Person("imperugo")
                {
                    FirstName = "Ugo",
                    LastName  = "Lattanzi"
                }
            };

            //var data = new List<dynamic>()
            //{
            //    new
            //    {
            //        Username = "******",
            //        FirstName = "Mauro",
            //        LastName = "Servienti"
            //    },

            //    new
            //    {
            //        Username = "******",
            //        FirstName = "Giorgio",
            //        LastName = "Formica"
            //    },

            //    new
            //    {
            //        Username = "******",
            //        FirstName = "Ugo",
            //        LastName = "Lattanzi"
            //    }
            //};

            ToggleCustomProperty = DelegateCommand.Create()
                                   .OnExecute(o =>
            {
                var temp = Items;
                Items    = null;
                this.OnPropertyChanged(() => Items);

                if (!temp.IsCustomPropertyDefined(propertyName))
                {
                    var prop = temp.AddCustomProperty <string>("Nome proprietà", obj =>
                    {
                        return(obj.Item.EntityItem.FirstName + " " + obj.Item.EntityItem.LastName);
                    });

                    propertyName = prop.Name;
                }
                else
                {
                    temp.RemoveCustomProperty(propertyName);
                }

                Items = temp;
                this.OnPropertyChanged(() => Items);
            });

            Items            = new EntityView <Person>(data);
            Items.AddingNew += (s, e) =>
            {
                e.NewItem = new Person("--empty--");
            };
        }
Example #25
0
        protected override IDelegateCommand GetCommand(DependencyObject target, DependencyProperty targetProperty)
        {
            if (this.Path != null && target is INotifyAttachedOjectLoaded)
            {
                var dataContext = (( INotifyAttachedOjectLoaded )target)
                                  .GetAttachedObject <FrameworkElement>()
                                  .DataContext;

                var path       = this.Path.Path;
                var methodName = path.EndsWith("Command") ? path.Remove(path.IndexOf("Command")) : path;
                var method     = dataContext.GetType().GetMethod(methodName);

                var def = dataContext.GetType()
                          .GetMethods()
                          .Where(mi => mi.Name.Equals(methodName))
                          .Select(mi =>
                {
                    var prms = mi.GetParameters();

                    return(new
                    {
                        FastDelegate = mi.CreateVoidDelegate(),
                        DataContext = dataContext,
                        HasParameter = prms.Length == 1,
                        ParameterType = prms.Length != 1 ? null : prms[0].ParameterType,
                        KeyBindings = mi.GetAttributes <KeyBindingAttribute>(),
                        Description = method.GetAttribute <CommandDescriptionAttribute>(),
                        Fact = dataContext.GetType()
                               .GetProperties()
                               .Where(pi => pi.PropertyType == typeof(Fact) && pi.Name.Equals("Can" + methodName))
                               .Select(pi => ( Fact )pi.GetValue(dataContext, null))
                               .SingleOrDefault()
                    });
                })
                          .SingleOrDefault();

                var text = (def.Description == null) ? String.Empty : def.Description.DisplayText;
                var cmd  = DelegateCommand.Create(text)
                           .OnCanExecute(o =>
                {
                    return(def.Fact != null ?
                           def.Fact.Eval(o) :
                           true);
                })
                           .OnExecute(o =>
                {
                    if (def.HasParameter)
                    {
                        var prm = Convert.ChangeType(o, def.ParameterType);
                        def.FastDelegate(def.DataContext, new[] { prm });
                    }
                    else
                    {
                        def.FastDelegate(def.DataContext, null);
                    }
                });

                if (def.KeyBindings != null)
                {
                    def.KeyBindings
                    .ForEach(kb => cmd.AddKeyGesture(kb.Key, kb.Modifiers));
                }

                if (def.Fact != null)
                {
                    cmd.AddMonitor(def.Fact);
                }

                target.SetValue(targetProperty, cmd);

                return(cmd);
            }

            return(null);
        }
        public DragAndDropSampleViewModel()
        {
            LeftPersons = new ObservableCollection <Person>()
            {
                new Person {
                    FirstName = "Mauro", LastName = "Servienti"
                },
                new Person {
                    FirstName = "Giovanni", LastName = "Rossi"
                },
                new Person {
                    FirstName = "Marco", LastName = "Verdi"
                },
            };
            RightPersons = new ObservableCollection <Person>();

            var dd = DelegateCommand.Create()
                     .OnCanExecute(state =>
            {
                var e = ( DragOverArgs )state;

                X = e.Position.X;
                Y = e.Position.Y;

                return(true);
            })
                     .OnExecute(state =>
            {
                var e = ( DropArgs )state;

                if (e.Data.GetDataPresent("left/person"))
                {
                    //dragging from left to right
                    var p = ( Person )e.Data.GetData("left/person");
                    LeftPersons.Remove(p);
                    RightPersons.Add(p);
                    if (LeftSelectedPerson == p)
                    {
                        LeftSelectedPerson = null;
                    }
                    RightSelectedPerson = p;
                }
                else if (e.Data.GetDataPresent("right/person"))
                {
                    //dragging from right to left
                    var p = ( Person )e.Data.GetData("right/person");
                    RightPersons.Remove(p);
                    LeftPersons.Add(p);
                    if (RightSelectedPerson == p)
                    {
                        RightSelectedPerson = null;
                    }
                    LeftSelectedPerson = p;
                }
                else
                {
                    //skip
                }
            });

            DropPerson = dd;
        }
Example #27
0
 public SampleViewModel()
 {
     AddItems = DelegateCommand.Create(AddItemsImpl);
 }