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

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

2024.03.14
XML
カテゴリ: C#.NET


以下は、C#とWPFを使用してMVVMパターンで`IDataErrorInfo`を利用するサンプルコードです。この例では、`Person`クラスのバリデーションに`IDataErrorInfo`を使用します。`Person`クラスには、名前と年齢のプロパティがあり、それぞれのプロパティに対して簡単なバリデーションを追加します。


まず、`Person`クラスを作成します。


```csharp

using System;

using System.ComponentModel;


public class Person : IDataErrorInfo

{

    private string name;

    public string Name

    {

        get { return name; }

        set { name = value; }

    }


    private int age;

    public int Age

    {

        get { return age; }

        set { age = value; }

    }


    public string this[string columnName]

    {

        get

        {

            string result = null;

            if (columnName == "Name")

            {

                if (string.IsNullOrWhiteSpace(Name))

                    result = "名前は必須です。";

            }

            else if (columnName == "Age")

            {

                if (Age < 0 || Age > 120)

                    result = "年齢は0から120の間でなければなりません。";

            }

            return result;

        }

    }


    public string Error => null;

}

```


次に、ビューモデルクラスを作成します。このビューモデルでは、`Person`オブジェクトをプロパティとして持ち、バリデーションエラーメッセージを表示します。


```csharp

using System.ComponentModel;

using System.Windows;


public class MainViewModel : ViewModelBase

{

    private Person person;


    public Person Person

    {

        get { return person; }

        set

        {

            person = value;

            OnPropertyChanged(nameof(Person));

        }

    }


    public MainViewModel()

    {

        Person = new Person();

    }


    public ICommand SaveCommand => new RelayCommand(Save, () => Person != null && string.IsNullOrWhiteSpace((Person as IDataErrorInfo).Error));


    private void Save()

    {

        MessageBox.Show("保存されました。");

    }

}

```


最後に、XAMLファイルでビューを作成します。


```xml

<Window x:Class="ValidationExample.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"

        xmlns:local="clr-namespace:ValidationExample"

        mc:Ignorable="d"

        Title="MainWindow" Height="450" Width="800">

    <Window.DataContext>

        <local:MainViewModel/>

    </Window.DataContext>

    <Grid>

        <Grid.RowDefinitions>

            <RowDefinition Height="Auto"/>

            <RowDefinition Height="Auto"/>

            <RowDefinition Height="Auto"/>

            <RowDefinition Height="Auto"/>

            <RowDefinition Height="Auto"/>

            <RowDefinition Height="Auto"/>

            <RowDefinition Height="Auto"/>

        </Grid.RowDefinitions>

        <Label Content="名前:" Grid.Row="0"/>

        <TextBox Text="{Binding Person.Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Grid.Row="0"/>

        <TextBlock Text="{Binding Person[Name], ValidatesOnDataErrors=True}" Foreground="Red" Grid.Row="1"/>


        <Label Content="年齢:" Grid.Row="2"/>

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

        <TextBlock Text="{Binding Person[Age], ValidatesOnDataErrors=True}" Foreground="Red" Grid.Row="3"/>


        <Button Content="保存" Command="{Binding SaveCommand}" Grid.Row="4"/>

    </Grid>

</Window>

```


このコードでは、`TextBox`のバインディングに`ValidatesOnDataErrors=True`を指定し、`TextBlock`にはバリデーションエラーメッセージが表示されるようにしています。また、保存ボタンの有効/無効状態は、`SaveCommand`の実行可能性に基づいて制御されています。






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

Last updated  2024.03.14 03:56:23


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

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