かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

Xamarin.Forms + Prism.Formsでダイアログを出す

Prism.Formsでは、IPageDialogServiceというインターフェースが提供されていて、ダイアログの表示もばっちりViewModelで出来るようになっています。

IPageDialogServiceには、DisplayAlertメソッドと、DisplayActionSheetメソッドが定義されています。DisplayAlertメソッドは単純なアラートダイアログを出して、DisplayActionSheetメソッドは選択肢を提供するメソッドになります。

DisplayActionSheetメソッドは、キャンセルのメッセージ、破棄のメッセージ、その他のメッセージの可変長引数という形になっています。さくっと使ってみましょう。

public class MainPageViewModel : BindableBase, INavigationAware
{
    private string _title;
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }
    }

    public DelegateCommand AlertCommand { get; }

    public DelegateCommand ConfirmCommand { get; }

    public MainPageViewModel(IPageDialogService pageDialogService)
    {
        this.AlertCommand = new DelegateCommand(async () =>
        {
            await pageDialogService.DisplayAlert("Title", "Hello world", "キャンセル");
        });

        this.ConfirmCommand = new DelegateCommand(async () =>
        {
            var result = await pageDialogService.DisplayActionSheet("Title",
                "キャンセル",
                "破棄",
                "やってやんよ",
                "やってやんよ2");
            await pageDialogService.DisplayAlert("選択したもの", result, "閉じる");
        });
    }

    public void OnNavigatedFrom(NavigationParameters parameters)
    {

    }

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

XAML側でボタンを2つおいて、Commandをバインドしておきます。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="PrismUnityApp9.Views.MainPage"
             Title="MainPage">
  <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
    <Label Text="{Binding Title}" />
    <Button Text="Alert"
            Command="{Binding AlertCommand}" />
    <Button Text="Confirm"
            Command="{Binding ConfirmCommand}" />
  </StackLayout>
</ContentPage>

実行すると、以下のようになります。

まず、DisplayAlertの場合。

f:id:okazuki:20160423122108p:plain

DisplayActionSheetの場合

f:id:okazuki:20160423122150p:plain