.NET MAUI データバインディング

beforeプログラミング

MAUIでのバインディングのメモ。たぶんWPFとほとんど変わらない。と思う。

XAML

MAUIのプロジェクト作成するとデフォルトで出来上がるXAMLを少し改変しLabel、Entry(1行テキスト入力)、Buttonを配置

<?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="MauiPartial.MainPage">

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

            <Label Text="{Binding InputText, Mode=OneWay}"/>
            <Entry
                x:Name="InputText"
                Text="{Binding InputText, Mode=TwoWay}"/>

            <Button
                x:Name="CounterBtn"
                Text="Click me"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnCounterClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

ビューモデルクラス

Entryに変更がある度にモデルクラスで変更値を受け取ります。今回の画面では入力がEntry(InputText)のみです。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace MauiPartial.Model
{
    public class MainPageModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged([CallerMemberName] string propertyName = null)
            => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        public string _InputText { set; get; }

        public string InputText
        {
            get => _InputText;
            set
            {
                if (_InputText != value)
                {
                    _InputText = value;
                    RaisePropertyChanged();
                }
            }
        }
    }
}

処理クラス

コンストラクタでBindingContextにビューモデルクラスを設定すると変更をビューモデルクラスに通知してくれます。
変更を受け取れているか確かめるためにボタン押下時にボタンの表示テキストを更新しています。

using MauiPartial.Model;

namespace MauiPartial;

public partial class MainPage : ContentPage
{
      int count = 0;

    private MainPageModel model;

    public MainPage()
      {
            InitializeComponent();
            model = new MainPageModel();
        this.BindingContext = model;
    }

    private void OnCounterClicked(object sender, EventArgs e)
    {
        CounterBtn.Text = $"{model.InputText}";
    }
}

実行するとこうなります。

before
after

参考

コメント

タイトルとURLをコピーしました