Quantcast
Channel: かずきのBlog@hatena
Viewing all articles
Browse latest Browse all 1387

Xamarin.Formsでボタンの2度押しをReactivePropertyを使って抑止してみよう

$
0
0

お題の通りです。

こんな感じでReactiveCommandを普通に使うと連打すると2重で画面遷移したりします。

using Prism.Mvvm;
using Prism.Navigation;
using Reactive.Bindings;
using System;

namespace PrismUnityApp12.ViewModels
{
    publicclass MainPageViewModel : BindableBase, INavigationAware
    {
        privatestring _title;
        publicstring Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        public ReactiveCommand NavigateCommand { get; }

        public MainPageViewModel(INavigationService navigationService)
        {
            this.NavigateCommand = new ReactiveCommand();
            this.NavigateCommand.Subscribe(async _ => await navigationService.NavigateAsync("NextPage"));
        }

        publicvoid OnNavigatedFrom(NavigationParameters parameters)
        {

        }

        publicvoid OnNavigatedTo(NavigationParameters parameters)
        {
            if (parameters.ContainsKey("title"))
                Title = (string)parameters["title"] + " and Prism";
        }
    }
}

解決策は簡単で2重起動防止機能が組み込まれてるAsyncReactiveCommandを使うだけでOKです。

using Prism.Mvvm;
using Prism.Navigation;
using Reactive.Bindings;
using System;

namespace PrismUnityApp12.ViewModels
{
    publicclass MainPageViewModel : BindableBase, INavigationAware
    {
        privatestring _title;
        publicstring Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        public AsyncReactiveCommand NavigateCommand { get; }

        public MainPageViewModel(INavigationService navigationService)
        {
            this.NavigateCommand = new AsyncReactiveCommand();
            this.NavigateCommand.Subscribe(async _ => await navigationService.NavigateAsync("NextPage"));
        }

        publicvoid OnNavigatedFrom(NavigationParameters parameters)
        {

        }

        publicvoid OnNavigatedTo(NavigationParameters parameters)
        {
            if (parameters.ContainsKey("title"))
                Title = (string)parameters["title"] + " and Prism";
        }
    }
}

これでOK。このCommandを紐づけがボタンを連打しても2重で画面遷移したりしなくなりました。名前の通りasyncに対応してるからばっちりですね。


Viewing all articles
Browse latest Browse all 1387

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>