全て
| カテゴリ未分類
| 通常
| 数学
| 投資
| 副業
| 転職・就職
| ブログ
| 株Stock
| VBA
| SharePoint
| REST API
| RenderListDataAsStream
| PowerAutomateDesktop
| Graph API
| PowerApps
| PowerAutomate
| PowerFx
| OfficeScriptオフィススクリプト
| PowerAutomate日時Excel日時相互関係
| PowerShell
| Dataverse
| UiPath
| OneDrive
| LINQ
| VB.NET
| C#.NET
| WPFC#.NET
| Git
カテゴリ: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
[C#.NET] カテゴリの最新記事
|