dnackのブログ

コード書く仕事の間にコード書いてる知命目前のおっさんです。

Prism/XamarinでAndroidアプリの作成(3):たかがボタン、されどボタン

ボタンを作成

UIにボタンとテキストを一つずつ追加して、ボタンを押すとテキストが書き換わるというチャチな仕組みを、Prismの仕組みを利用して書いてみることにする。

まずは、Viewの変更。

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SamplePrismApp.Views.MainPage"
             Title="{Binding Title}">

    <StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
        <Label Text="Welcome to Xamarin Forms and Prism!" />
        <Label Text="{Binding TextMessage.Value} "/>
        <Button Text="ButtonA" Command="{Binding ButtonACommand}"/>
    </StackLayout>

</ContentPage>

LabelのテキストとButtonのコマンドにBinding がついているが、これはTitleと同じように実体をViewModelに送り込むためのおまじない(とでも思っておけばいい)。

Labelのテキストの実体であるTextMessage.ValueValueが気になるが、これはTextMessageをstring型ではなく、ReactiveProperty<string>型で定義するから、ReactiveProperty型のTextMessageではなく、そのメンバのValueを実態に指定する必要があるためだ。これもまあ、当面はReactiveProperty使うためのおまじないと思っていればいいかもしれない。

Viewの変更は以上。MainPage.xaml.csの変更は不要。

 

続いてViewModel。

MainPageViewModelはこんな感じ

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


namespace SamplePrismApp.ViewModels
{
    public class MainPageViewModel : ViewModelBase
    {
        public ReactiveProperty<string> TextMessage { get; set; }
        public DelegateCommand ButtonACommand { get; set; }

        public MainPageViewModel(INavigationService navigationService)
            : base(navigationService)
        {
            Title = "Main Page";
            TextMessage = new ReactiveProperty<string>("0000");
            ButtonACommand = new DelegateCommand(ButtonAClicked);
        }

        private void ButtonAClicked()
        {
            TextMessage.Value = "XXXX";
        }
    }
}

データバインディングにReactivePropertyを入れるので、using句using Reactive.Bindings;を追加。

Viewに追加したTextMessage、ButtonACommandの実体をそれぞれ定義してコンストラクタの中で初期化している。

ButtonAタップ時の動作は、ButtonAClickedというメソッドの中で定義して、初期化時にデリゲートに登録している。コマンドの中身は単にテキストを切り替えるだけのもの。

起動時が右、ボタンをタップしたら左画面になる。

f:id:dnack:20210902165620p:plain
f:id:dnack:20210902165623p:plain

 

本当にちょっとした例だけど、PrismでUI要素足すときの作業としてはほとんどこれの応用になる。

さあこれでがんがんPrismのプログラム書けるよ。

 

というわけで次回に続く。多分。