最終更新:2019年5月29日
Xamarin.Formsを使ってMVVMアーキテクチャにする場合、ViewModelからDisplayAlertを呼び出す方法がわからなくて困っていたのですが、実現する方法がありました。
環境
Visual Studio Community 2019 for Mac
Xamarin.Forms (3.6.0.264807)
手順
やり方は意外に簡単でApplication.Current.MainPage.DisplayAlert
をViewModelで使うだけです。
引数を3つにするとキャンセルボタンだけのアラート、4つにするとBool値を返すことができます。
docs.microsoft.com
以下、サンプルコードです。 (コードビハインドはInitializeComponent()
のみなので省略しています)
View(MainPage.xaml.cs)
<?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:local="clr-namespace:DisplayAlertFromViewModel" x:Class="DisplayAlertFromViewModel.MainPage"> <ContentPage.BindingContext> <local:MainPageViewModel/> </ContentPage.BindingContext> <StackLayout> <Button Text="Alert" Command="{Binding OnButton}" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" /> </StackLayout> </ContentPage>
ViewModel(MainPageViewModel.cs)
using Xamarin.Forms; namespace DisplayAlertFromViewModel { public class MainPageViewModel { public MainPageViewModel() { OnButton = new Command(async() => { var select = await Application.Current.MainPage.DisplayAlert("Alert", "アラートです", "OK","キャンセル"); if (select) await Application.Current.MainPage.DisplayAlert("Alert", "OKが選択されました", "終了"); else await Application.Current.MainPage.DisplayAlert("Alert", "キャンセルが選択されました", "終了"); }); } public Command OnButton { get; } } }
以下のような動きになります。
これを使えばMVVMなアプリを作りやすくなりそうですね!