.NET MAUIでReactivePropertyを試す

C# コンピュータ
C#
.NET MAUIのプロジェクトでデータバインディングをしようと思うのですが、ReactivePropertyパッケージの力を借りたいと思います。

ReactivePropertyをインストール

NuGetでReactivePropertyをインストール
Visual Studio 2022のメニュー→「プロジェクト」→「NuGetパッケージの管理」
ReactivePropertyを検索しインストール
System.Reactiveを検索しインストール

ソースコード

ファイル名:MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ReactivePropertySample.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Label
                Text="名前"
                FontSize="32"
                HorizontalOptions="Center" />
            <Entry Text="{Binding Name.Value}" />
            <Button
                Text="送信"
                Command="{Binding OnSubmitClicked}"
                HorizontalOptions="Center" />
            <Label
                Text="{Binding Message.Value}"
                FontSize="18" />

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

ファイル名:MainPage.xaml.cs

namespace ReactivePropertySample;

public partial class MainPage
{
    ViewModel _vm;
    public MainPage()
    {
        InitializeComponent();
        this.Loaded += MainPage_Loaded;
    }
    private void MainPage_Loaded(object sender, EventArgs e)
    {
        _vm = new ViewModel();
        _vm.Name.Value = "太郎";

        this.BindingContext = _vm;
    }
}

ファイル名:ViewModel.cs

using Reactive.Bindings;
using System.Windows.Input;

namespace ReactivePropertySample;

internal class ViewModel
{
    public ReactiveProperty<string> Name { get; } = new ReactiveProperty<string>("");
    public ReactiveProperty<string> Message { get; } = new ReactiveProperty<string>("");
    public ReactiveCommand OnSubmitClicked { get; }

    //public ICommand OnClickSubmit { get; private set; }
    public ViewModel()
    {
        OnSubmitClicked = new ReactiveCommand().WithSubscribe(() => {
            Message.Value = String.Format("クリックボタンが押された。名前:{0}", Name.Value);
        });
    }
}

実行

名前を変更し「送信」ボタンをクリック
LabelにMessageが表示される。

感想

MainPage.xamlEntryViewModel.csNameプロパティにバインドしています。
また、MainPage.xamlButtonViewModel.csOnSubmitClickedプロパティにバインドしています。ViewModel()コンストラクタ内でOnSubmitClickedプロパティにnew ReactiveCommand().WithSubscribe();Buttonを押した場合の実行するコードをラムダ式で記述しています。

コメント