示例#1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HeaderViewModel"/> class.
        /// </summary>
        /// <param name="powerService">The power service implementation.</param>
        /// <param name="titleService">The title service.</param>
        /// <param name="policyProvider">The policy provider to execute ordinary commands.</param>
        /// <param name="navigationManager">The navigation manager to navigate to a different page.</param>
        public HeaderViewModel(
            IPowerService powerService,
            ITitleService titleService,
            ICommandPolicyProvider policyProvider,
            NavigationManager navigationManager)
        {
            if (powerService is null)
            {
                throw new ArgumentNullException(nameof(powerService));
            }

            if (titleService is null)
            {
                throw new ArgumentNullException(nameof(titleService));
            }

            if (policyProvider is null)
            {
                throw new ArgumentNullException(nameof(policyProvider));
            }

            if (navigationManager is null)
            {
                throw new ArgumentNullException(nameof(navigationManager));
            }

            this.WhenActivated(disposable =>
            {
                this.poweredOn = powerService.PoweredOn.ToProperty(this, x => x.PoweredOn).DisposeWith(disposable);
                this.title     = titleService.Title.ToProperty(this, x => x.Title).DisposeWith(disposable);
                var policy     = policyProvider.GetPolicy();

                this.TogglePower = ReactiveCommand.CreateFromTask(async(ct) =>
                {
                    switch (this.PoweredOn)
                    {
                    case true:
                        await policy.ExecuteAsync(
                            async(token) => await powerService.PowerOff(token),
                            ct);
                        break;

                    case false:
                        await policy.ExecuteAsync(
                            async(token) => await powerService.PowerOn(token),
                            ct);
                        break;
                    }
                }).DisposeWith(disposable);

                this.Settings = ReactiveCommand.Create(() =>
                {
                    navigationManager.NavigateTo("/Settings");
                }).DisposeWith(disposable);

                this.canExecuteTogglePower = this.TogglePower.CanExecute.ToProperty(this, x => x.CanExecuteTogglePower).DisposeWith(disposable);
            });
        }