「東雲 忠太郎」の平凡な日常のできごと

「東雲 忠太郎」の平凡な日常のできごと

2024.06.08
XML
カテゴリ: WPFC#.NET


WPFのMVVMモデルで入力チェックを実装するには、主に以下の要素が必要です:


1. **Model**:データ構造を定義します。

2. **ViewModel**:データとロジックを持ち、ビューにバインディングされます。



さらに、入力チェックを行うためには、`IDataErrorInfo`または`INotifyDataErrorInfo`インターフェースを使用します。ここでは、`IDataErrorInfo`を使用した簡単なサンプルコードを示します。


### 1. Model

まず、データ構造を定義します。ここでは、`IDataErrorInfo`インターフェースを実装して入力チェックを行います。


```csharp

using System.ComponentModel;


public class Person : IDataErrorInfo

{

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int Age { get; set; }


    public string this[string columnName]

    {

        get

        {

            string result = null;

            switch (columnName)

            {

                case nameof(FirstName):

                    if (string.IsNullOrWhiteSpace(FirstName))

                    {

                        result = "First name cannot be empty.";

                    }

                    break;

                case nameof(LastName):

                    if (string.IsNullOrWhiteSpace(LastName))

                    {

                        result = "Last name cannot be empty.";

                    }

                    break;

                case nameof(Age):

                    if (Age <= 0 || Age > 120)

                    {

                        result = "Age must be between 1 and 120.";

                    }

                    break;

            }

            return result;

        }

    }


    public string Error => null;

}

```


### 2. ViewModel

次に、ViewModelを定義します。ViewModelはModelを持ち、ビューにバインディングされます。


```csharp

using System.ComponentModel;

using System.Runtime.CompilerServices;


public class PersonViewModel : INotifyPropertyChanged

{

    private Person _person;


    public PersonViewModel()

    {

        _person = new Person();

    }


    public string FirstName

    {

        get => _person.FirstName;

        set

        {

            _person.FirstName = value;

            OnPropertyChanged();

            OnPropertyChanged(nameof(Error));

        }

    }


    public string LastName

    {

        get => _person.LastName;

        set

        {

            _person.LastName = value;

            OnPropertyChanged();

            OnPropertyChanged(nameof(Error));

        }

    }


    public int Age

    {

        get => _person.Age;

        set

        {

            _person.Age = value;

            OnPropertyChanged();

            OnPropertyChanged(nameof(Error));

        }

    }


    public string Error => _person.Error;


    public string this[string columnName] => _person[columnName];


    public event PropertyChangedEventHandler PropertyChanged;


    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)

    {

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

    }

}

```


### 3. View

最後に、ビュー(XAMLファイル)を定義します。ここでは、バインディングとエラーテンプレートを使用して、入力チェックのエラーを表示します。


```xml

<Window x:Class="WpfApp.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        mc:Ignorable="d"

        Title="MainWindow" Height="200" Width="400">

    <Window.DataContext>

        <local:PersonViewModel />

    </Window.DataContext>

    <Grid Margin="10">

        <Grid.RowDefinitions>

            <RowDefinition Height="Auto" />

            <RowDefinition Height="Auto" />

            <RowDefinition Height="Auto" />

            <RowDefinition Height="Auto" />

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="Auto" />

            <ColumnDefinition Width="*" />

        </Grid.ColumnDefinitions>


        <TextBlock Text="First Name:" VerticalAlignment="Center" />

        <TextBox Grid.Column="1" Text="{Binding FirstName, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}">

            <TextBox.Style>

                <Style TargetType="TextBox">

                    <Style.Triggers>

                        <Trigger Property="Validation.HasError" Value="True">

                            <Setter Property="ToolTip" Value="{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={RelativeSource Self}}" />

                        </Trigger>

                    </Style.Triggers>

                </Style>

            </TextBox.Style>

        </TextBox>


        <TextBlock Grid.Row="1" Text="Last Name:" VerticalAlignment="Center" />

        <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding LastName, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}">

            <TextBox.Style>

                <Style TargetType="TextBox">

                    <Style.Triggers>

                        <Trigger Property="Validation.HasError" Value="True">

                            <Setter Property="ToolTip" Value="{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={RelativeSource Self}}" />

                        </Trigger>

                    </Style.Triggers>

                </Style>

            </TextBox.Style>

        </TextBox>


        <TextBlock Grid.Row="2" Text="Age:" VerticalAlignment="Center" />

        <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Age, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}">

            <TextBox.Style>

                <Style TargetType="TextBox">

                    <Style.Triggers>

                        <Trigger Property="Validation.HasError" Value="True">

                            <Setter Property="ToolTip" Value="{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={RelativeSource Self}}" />

                        </Trigger>

                    </Style.Triggers>

                </Style>

            </TextBox.Style>

        </TextBox>

    </Grid>

</Window>

```


### 完成したコード

このサンプルでは、`FirstName`、`LastName`、`Age`の入力チェックを行い、エラーがある場合にはツールチップとしてエラーメッセージを表示します。入力チェックのロジックはモデル内で実装され、ビューはViewModelにバインディングされてデータを表示および編集します。






お気に入りの記事を「いいね!」で応援しよう

Last updated  2024.06.08 20:51:59


【毎日開催】
15記事にいいね!で1ポイント
10秒滞在
いいね! -- / --
おめでとうございます!
ミッションを達成しました。
※「ポイントを獲得する」ボタンを押すと広告が表示されます。
x

© Rakuten Group, Inc.
Design a Mobile Website
スマートフォン版を閲覧 | PC版を閲覧
Share by: