当前位置: 首页>>代码示例>>C#>>正文


C# ReactiveCommand.Execute方法代码示例

本文整理汇总了C#中ReactiveCommand.Execute方法的典型用法代码示例。如果您正苦于以下问题:C# ReactiveCommand.Execute方法的具体用法?C# ReactiveCommand.Execute怎么用?C# ReactiveCommand.Execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ReactiveCommand的用法示例。


在下文中一共展示了ReactiveCommand.Execute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ReactiveCommandAllFlow

        public void ReactiveCommandAllFlow()
        {
            var testScheduler = new TestScheduler();
            var @null = (object)null;
            var recorder1 = testScheduler.CreateObserver<object>();
            var recorder2 = testScheduler.CreateObserver<object>();

            var cmd = new ReactiveCommand();
            cmd.Subscribe(recorder1);
            cmd.Subscribe(recorder2);

            cmd.CanExecute().Is(true);
            cmd.Execute(); testScheduler.AdvanceBy(10);
            cmd.Execute(); testScheduler.AdvanceBy(10);
            cmd.Execute(); testScheduler.AdvanceBy(10);

            cmd.Dispose();
            cmd.CanExecute().Is(false);

            cmd.Dispose(); // dispose again

            recorder1.Messages.Is(
                OnNext(0, @null),
                OnNext(10, @null),
                OnNext(20, @null),
                OnCompleted<object>(30));

            recorder2.Messages.Is(
                OnNext(0, @null),
                OnNext(10, @null),
                OnNext(20, @null),
                OnCompleted<object>(30));
        }
开发者ID:wada811,项目名称:ReactiveProperty,代码行数:33,代码来源:ReactiveCommandTest.cs

示例2: PersonListViewModel

 public PersonListViewModel(IScreen hostScreen, IPersonRepository personRepository = null)
 {
     HostScreen = hostScreen;
     personRepository = personRepository ?? new PersonRepository();
     Persons = new ReactiveList<PersonItemViewModel>();
     NewPersonCommand = new ReactiveCommand(null);
     NewPersonCommand.RegisterAsyncAction(_ => { }).Subscribe(_ => HostScreen.Router.Navigate.Execute(new PersonAddViewModel(HostScreen)));
     RefreshCommand = new ReactiveCommand(null);
     var refresh = RefreshCommand.RegisterAsync<List<Person>>(_ => Observable.Start(() => personRepository.RetrievePersonsAsync().
                                                                                                           Result));
     refresh.Subscribe(list =>
     {
         using (Persons.SuppressChangeNotifications())
         {
             Persons.Clear();
             Persons.AddRange(personRepository.RetrievePersonsAsync().
                                               Result.Select(d => new PersonItemViewModel(d.FirstName,
                                                                      d.LastName,
                                                                      d.Age)));
         }
     });
     MessageBus.Current.Listen<Person>().
                Subscribe(p =>
                {
                    personRepository.AddPerson(p);
                    RefreshCommand.Execute(null);
                });
 }
开发者ID:jiravanet,项目名称:Prezentace-ReactiveUI,代码行数:28,代码来源:PersonListViewModel.cs

示例3: SessionViewModel

        public SessionViewModel(SessionModel model ,IPersonFactory<Person> personFactory)
        {
            _model = model.ThrowIfNull("model");
            _personFactory = personFactory.ThrowIfNull("personFactory");

            AddNewPersonCommand = new ReactiveCommand();
            AddNewPersonCommand.Subscribe(dontcare =>
                _model.Participants.Add(_personFactory.GetNewPerson(Participants.Count)));

            Participants = _model.Participants
                                    .CreateDerivedCollection(x => new ParticipantViewModel(x));

            Participants.ChangeTrackingEnabled = true;

            var deleteCanExecute = Observable.Merge(Participants.ItemChanged
                                                 .Select(_ => Participants.Any(p => p.IsSelected)),
                                             Participants.CollectionCountChanged
                                             .Select(_ => Participants.Any(p=> p.IsSelected)));

            DeleteSelectedCommand = new ReactiveCommand
                (
                       deleteCanExecute
                );
            DeleteSelectedCommand.Subscribe(
                x =>
                    {
                        RemoveSelected();
                    }
                );

            AddNewPersonCommand.Execute(null);
        }
开发者ID:asizikov,项目名称:PiratesBay,代码行数:32,代码来源:SessionViewModel.cs

示例4: ServiceViewModel

        public ServiceViewModel(ServiceBase service)
        {
            Name = service.ServiceName;

            //Get an observable for the current state
            var currentStateObs = this.ObservableForProperty(x => x.CurrentState).Value().StartWith(ServiceState.Stopped);

            //Map an observable to IsBusy that is True if the current state is *ing
            currentStateObs.Select
            (
                s => s == ServiceState.Pausing ||
                     s == ServiceState.Starting ||
                     s == ServiceState.Stopping
            )
            .Subscribe(busy => IsBusy = busy);

            StartCommand    = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Stopped));
            StopCommand     = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Started || s == ServiceState.Paused));
            PauseCommand    = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Started && service.CanPauseAndContinue));
            ContinueCommand = new ReactiveCommand(currentStateObs.Select(s => s == ServiceState.Paused && service.CanPauseAndContinue));

            AssignmentSubscription(StartCommand,    () => ServiceBaseHelpers.StartService(service));
            AssignmentSubscription(StopCommand,     () => ServiceBaseHelpers.StopService(service));
            AssignmentSubscription(PauseCommand,    () => ServiceBaseHelpers.PauseService(service));
            AssignmentSubscription(ContinueCommand, () => ServiceBaseHelpers.ContinueService(service));

            //
            // Start on start time
            //
            StartCommand.Execute(null);
        }
开发者ID:Behzadkhosravifar,项目名称:SignalR,代码行数:31,代码来源:ServiceViewModel.cs

示例5: AllowConcurrentExecutionTest

        public void AllowConcurrentExecutionTest()
        {
            (new TestScheduler()).With(sched => {
                var fixture = new ReactiveCommand(null, true, sched);

                Assert.True(fixture.CanExecute(null));

                var result = fixture.RegisterAsync(_ => Observable.Return(4).Delay(TimeSpan.FromSeconds(5), sched))
                    .CreateCollection();
                Assert.Equal(0, result.Count);

                sched.AdvanceToMs(25);
                Assert.Equal(0, result.Count);

                fixture.Execute(null);
                Assert.True(fixture.CanExecute(null));
                Assert.Equal(0, result.Count);

                sched.AdvanceToMs(2500);
                Assert.True(fixture.CanExecute(null));
                Assert.Equal(0, result.Count);

                sched.AdvanceToMs(5500);
                Assert.True(fixture.CanExecute(null));
                Assert.Equal(1, result.Count);
            });
        }
开发者ID:niefan,项目名称:ReactiveUI,代码行数:27,代码来源:ReactiveCommandTest.cs

示例6: CompletelyDefaultReactiveCommandShouldFire

        public void CompletelyDefaultReactiveCommandShouldFire()
        {
            var sched = new TestScheduler();
            var fixture = new ReactiveCommand(null, sched);
            Assert.IsTrue(fixture.CanExecute(null));

            string result = null;
            fixture.Subscribe(x => result = x as string);

            fixture.Execute("Test");
            sched.Start();
            Assert.AreEqual("Test", result);
            fixture.Execute("Test2");
            sched.Start();
            Assert.AreEqual("Test2", result);
        }
开发者ID:anurse,项目名称:MetroRx,代码行数:16,代码来源:ReactiveCommandTest.cs

示例7: CanExecuteShouldChangeOnInflightOp

        public void CanExecuteShouldChangeOnInflightOp()
        {
            (new TestScheduler()).With(sched => {
                var canExecute = sched.CreateHotObservable(
                    sched.OnNextAt(0, true),
                    sched.OnNextAt(250, false),
                    sched.OnNextAt(500, true),
                    sched.OnNextAt(750, false),
                    sched.OnNextAt(1000, true),
                    sched.OnNextAt(1100, false)
                    );

                var fixture = new ReactiveCommand(canExecute);
                int calculatedResult = -1;
                bool latestCanExecute = false;

                fixture.RegisterAsync(x =>
                    Observable.Return((int)x*5).Delay(TimeSpan.FromMilliseconds(900), RxApp.MainThreadScheduler))
                    .Subscribe(x => calculatedResult = x);

                fixture.CanExecuteObservable.Subscribe(x => latestCanExecute = x);

                // CanExecute should be true, both input observable is true
                // and we don't have anything inflight
                sched.AdvanceToMs(10);
                Assert.True(fixture.CanExecute(1));
                Assert.True(latestCanExecute);

                // Invoke a command 10ms in
                fixture.Execute(1);

                // At 300ms, input is false
                sched.AdvanceToMs(300);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);

                // At 600ms, input is true, but the command is still running
                sched.AdvanceToMs(600);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);

                // After we've completed, we should still be false, since from
                // 750ms-1000ms the input observable is false
                sched.AdvanceToMs(900);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);
                Assert.Equal(-1, calculatedResult);

                sched.AdvanceToMs(1010);
                Assert.True(fixture.CanExecute(1));
                Assert.True(latestCanExecute);
                Assert.Equal(calculatedResult, 5);

                sched.AdvanceToMs(1200);
                Assert.False(fixture.CanExecute(1));
                Assert.False(latestCanExecute);
            });
        }
开发者ID:niefan,项目名称:ReactiveUI,代码行数:58,代码来源:ReactiveCommandTest.cs

示例8: DispatchViewModel

        public DispatchViewModel(IScreen screen, ISession session)
        {
            HostScreen = screen;
            GoBack = HostScreen.Router.NavigateBack;

            Techs = new ReactiveList<Employee>();
            Tickets = new ReactiveList<Ticket>();

            var getFreshTechs = new ReactiveCommand();
            getFreshTechs.ObserveOn(RxApp.MainThreadScheduler).Subscribe(_ =>
                {
                    Techs.Clear();
                    session.FetchResults<Employee>()
                        .ObserveOn(RxApp.MainThreadScheduler)
                        .Subscribe(x => Techs.Add(x));
                });

            var getFreshTickets = new ReactiveCommand();
            getFreshTickets.ObserveOn(RxApp.MainThreadScheduler).Subscribe(_ =>
                {
                    Tickets.Clear();
                    session.FetchResults<Ticket>()
                        .ObserveOn(RxApp.MainThreadScheduler)
                        .Subscribe(x => Tickets.Add(x));
                });

            Refresh = new ReactiveCommand(session.IsWorking.Select(x => !x));
            Refresh.Subscribe(_ =>
                {
                    getFreshTechs.Execute(default(object));
                    getFreshTickets.Execute(default(object));
                });

            Assign = new ReactiveCommand(Observable.CombineLatest(
                this.WhenAny(
                    x => x.SelectedEmployee,
                    y => y.SelectedTicket,
                    (x, y) => x.Value != null && y.Value != null),
                Refresh.CanExecuteObservable,
                (x, y) => x && y));
            Assign.Subscribe(_ =>
            {
                using (session.ScopedChanges())
                {
                    var eventTaker = session.Take<TicketEvent>();
                    eventTaker.Add(new TicketEvent { Employee = SelectedEmployee, Ticket = SelectedTicket, TicketStatus = TicketStatus.Assigned, Time = DateTime.Now });
                }
            });

            _error = session.ThrownExceptions
                .Select(x => x.Message)
                .ObserveOn(RxApp.MainThreadScheduler)
                .ToProperty(this, x => x.Error);

            Refresh.Execute(default(object));
        }
开发者ID:pingortle,项目名称:CompsysTicketingPlayground,代码行数:56,代码来源:DispatchViewModel.cs

示例9: CommandCanExecute_Test

 public void CommandCanExecute_Test()
 {
     //Given
     string result = null;
     string expected = Any.Create<string>();
     ICommand command = new ReactiveCommand<string>(t => result = t, _ => false);
     //When
     bool canExecute = command.CanExecute(null);
     command.Execute(expected);
     //Then
     Assert.That(canExecute, Is.False);
     Assert.That(result, Is.Null);
 }
开发者ID:mmpyro,项目名称:RxLightFramework,代码行数:13,代码来源:ReactiveCommand_Specyfication.cs

示例10: Command_Test

 public void Command_Test()
 {
     //Given
     string result = null;
     string expected = Any.Create<string>();
     ICommand command = new ReactiveCommand<string>(t => result = t, _ => true);
     //When
     bool canExecute = command.CanExecute(null);
     command.Execute(expected);
     //Then
     Assert.That(expected, Is.EqualTo(result));
     Assert.That(canExecute, Is.True);
 }
开发者ID:mmpyro,项目名称:RxLightFramework,代码行数:13,代码来源:ReactiveCommand_Specyfication.cs

示例11: SettingsWindowViewModel

        public SettingsWindowViewModel()
        {
            CloseCommand = new ReactiveCommand();
              ExceptionCommand = new ReactiveCommand();

              KeyCommand = new ReactiveCommand();
              KeyCommand.Subscribe(x => {
            var tuple = x as Tuple<string, HotKey>;
            if (tuple.Item2 == null)
              return;

            App.HotKeyManager.Unregister(Settings.ScreenKey);
            App.HotKeyManager.Unregister(Settings.SelectionKey);

            var tmpScreenKey = Settings.ScreenKey;
            var tmpSelectionKey = Settings.SelectionKey;
            switch (tuple.Item1) {
              case "ScreenKey":
            tmpScreenKey = tuple.Item2;
            break;
              case "SelectionKey":
            tmpSelectionKey = tuple.Item2;
            break;
            }

            App.HotKeyManager.Register(tmpScreenKey);
            App.HotKeyManager.Register(tmpSelectionKey);

            // Only apply the change if there hasn't been an error registering them
            Settings.GetType().GetProperty(tuple.Item1).SetValue(Settings, tuple.Item2);
              });
              KeyCommand.ThrownExceptions.Subscribe(ex => {
            // We have to re-register the hotkeys here so
            // that both are registered with the system
            App.HotKeyManager.Unregister(Settings.ScreenKey);
            App.HotKeyManager.Unregister(Settings.SelectionKey);
            App.HotKeyManager.Register(Settings.ScreenKey);
            App.HotKeyManager.Register(Settings.SelectionKey);

            ExceptionCommand.Execute(ex);
              });

              App.Settings.Changed.Subscribe(_ => this.RaisePropertyChanged("Settings"));
        }
开发者ID:vevix,项目名称:Pixel,代码行数:44,代码来源:SettingsWindowViewModel.cs

示例12: FullCommand_Test

 public void FullCommand_Test()
 {
     //Given
     const string message = "Reactive";
     string result = null;
     bool completed = false;
     Exception exception = null;
     string expected = Any.Create<string>();
     var command = new ReactiveCommand<string>(t => result = t, _ => true,ex => exception = ex,() => completed = true );
     //When
     bool canExecute = command.CanExecute(null);
     command.Execute(expected);
     command.OnError(new Exception(message));
     command.OnCompleted();
     //Then
     Assert.True(canExecute);
     Assert.AreEqual(result, expected);
     Assert.That(exception.Message, Is.EqualTo(message));
     Assert.True(completed);
 }
开发者ID:mmpyro,项目名称:RxLightFramework,代码行数:20,代码来源:ReactiveCommand_Specyfication.cs

示例13: ObservableExecuteFuncShouldBeObservableAndAct

        public void ObservableExecuteFuncShouldBeObservableAndAct()
        {
            var executed_params = new List<object>();
            var fixture = new ReactiveCommand();
            fixture.Subscribe(x => executed_params.Add(x));

            var observed_params = new ReplaySubject<object>();
            fixture.Subscribe(observed_params.OnNext, observed_params.OnError, observed_params.OnCompleted);

            var range = Enumerable.Range(0, 5);
            foreach (var v in range) fixture.Execute(v);

            Assert.AreEqual(range.Count(), executed_params.Count);
            foreach (var v in range.Zip(executed_params.OfType<int>(), (e, a) => new { e, a })) {
                Assert.AreEqual(v.e, v.a);
            }

            range.ToObservable()
                .Zip(observed_params, (expected, actual) => new { expected, actual })
                .Subscribe(x => Assert.AreEqual(x.expected, x.actual));
        }
开发者ID:anurse,项目名称:MetroRx,代码行数:21,代码来源:ReactiveCommandTest.cs

示例14: PreviewWindowViewModel

        public PreviewWindowViewModel(string file)
        {
            ImageSource = file;
              SaveDlgCommand = new ReactiveCommand();
              CloseCommand = new ReactiveCommand();

              UploadCommand = new ReactiveCommand();
              UploadCommand.Subscribe(async _ => {
            CloseCommand.Execute(null);
            await App.Uploader.Upload(file);
              });

              SaveFileCommand = new ReactiveCommand();
              SaveFileCommand.Subscribe(async x => {
            var saveFile = x as string;
            if (String.IsNullOrEmpty(saveFile))
              return;
            await Task.Run(() => {
              using (var image = new Bitmap(ImageSource)) {
            switch (App.Settings.ImageFormat) {
              case ImageFormats.Png:
                image.Save(saveFile, ImageFormat.Png);
                break;
              case ImageFormats.Jpg:
                var encoder = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
                using (var encParams = new EncoderParameters(1)) {
                  encParams.Param[0] = new EncoderParameter(Encoder.Quality, App.Settings.ImageQuality);
                  if (encoder != null)
                    image.Save(saveFile, encoder, encParams);
                }
                break;
              case ImageFormats.Bmp:
                image.Save(saveFile, ImageFormat.Bmp);
                break;
            }
              }
            });
              });
        }
开发者ID:vevix,项目名称:Pixel,代码行数:39,代码来源:PreviewWindowViewModel.cs

示例15: Initialize

        private void Initialize(string dataType, string componentType, string portName)
        {
            UpdateDataTypeCommand = new ReactiveCommand();
            UpdatePortNameCommand = new ReactiveCommand();
            UpdateCompoentTypeCommand = new ReactiveCommand();

            DataTypes = UpdateDataTypeCommand
                .SelectMany(_=>Observable.Start(()=>_recordDescriptionRepository.GetDataTypes(componentType,portName))
                    .Catch((Exception ex) => Messenger.Raise(new InformationMessage("データベースアクセスに失敗しました。", "エラー", "ShowError"))))
                .Do(_ => DataTypes.ClearOnScheduler())
                .SelectMany(_=>_)
                .ToReactiveCollection();

            PortNames = UpdatePortNameCommand
                .SelectMany(_=>Observable.Start(()=>_recordDescriptionRepository.GetPortNames(dataType,componentType))
                    .Catch((Exception ex) => Messenger.Raise(new InformationMessage("データベースアクセスに失敗しました。", "エラー", "ShowError"))))
                .Do(_ => PortNames.ClearOnScheduler())
                .SelectMany(_=>_)
                .ToReactiveCollection();
            ComponentTypes = UpdateCompoentTypeCommand
                .SelectMany(_=>Observable.Start(()=>_recordDescriptionRepository.GetComponentTypes(dataType,portName))
                    .Catch((Exception ex) => Messenger.Raise(new InformationMessage("データベースアクセスに失敗しました。", "エラー", "ShowError"))))
                .Do(_ => ComponentTypes.ClearOnScheduler())
                .SelectMany(_=>_)
                .ToReactiveCollection();

            DataType = dataType;
            PortName = portName;
            ComponentType = componentType;

            UpdateDataTypeCommand.Execute(null);
            UpdatePortNameCommand.Execute(null);
            UpdateCompoentTypeCommand.Execute(null);
        }
开发者ID:zoetrope,项目名称:RtStorage,代码行数:34,代码来源:SearchRecordWindowViewModel.cs


注:本文中的ReactiveCommand.Execute方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。