599894 ランダム
 HOME | DIARY | PROFILE 【フォローする】 【ログイン】

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

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

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


IDataErrorInfo インターフェースを使用して、入力値の検証を行うサンプルコードを提供します。この例では、ViewModel 内で IDataErrorInfo インターフェースを実装して、入力値の検証を行います。


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


```csharp

using System;

using System.ComponentModel;

using System.Runtime.CompilerServices;


public class MainViewModel : INotifyPropertyChanged, IDataErrorInfo

{

    private string _name;

    public string Name

    {

        get { return _name; }

        set

        {

            _name = value;

            OnPropertyChanged();

        }

    }


    public string this[string columnName]

    {

        get

        {

            if (columnName == "Name")

            {

                if (string.IsNullOrWhiteSpace(Name))

                    return "Name cannot be empty.";

                // 他の検証ロジックを追加することもできます。

            }

            return null;

        }

    }


    public string Error

    {

        get { return null; }

    }


    public event PropertyChangedEventHandler PropertyChanged;


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

    {

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

    }

}

```


次に、MainWindow.xaml ファイルに TextBox を追加し、ViewModel のプロパティとバインディングします。


```xml

<Window x:Class="WpfDataErrorInfoExample.MainWindow"

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

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

        xmlns:local="clr-namespace:WpfDataErrorInfoExample"

        Title="MainWindow" Height="150" Width="300">

    <Grid>

        <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" Margin="10"/>

        <TextBlock Text="{Binding (Validation.Errors)[0].ErrorContent, ElementName=textBoxName}" Foreground="Red" Margin="10,0,0,0"/>

    </Grid>

</Window>

```


最後に、MainWindow.xaml.cs ファイルで ViewModel を作成し、DataContext として設定します。


```csharp

public partial class MainWindow : Window

{

    public MainWindow()

    {

        InitializeComponent();

        DataContext = new MainViewModel();

    }

}

```


これで、C# WPF アプリケーションで IDataErrorInfo を使用して入力値の検証を行う準備が整いました。入力値が検証に適合しない場合は、エラーメッセージが表示されます。






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

Last updated  2024.03.18 07:56:55



© Rakuten Group, Inc.