Validationコントロールの利用 †Validationコントロールを利用するために、データモデルを下記のように宣言する必要があります。 using System.ComponentModel; using System.ComponentModel.DataAnnotations; public class Users : INotifyPropertyChanged { //ここはポイント //_userNameの値を空のままに private string _userName; /// <summary> /// ユーザ名を取得・設定します。 /// </summary> [Required(ErrorMessage = "UserNameが必須項目です。")] [StringLength(20, ErrorMessage = "最大20文字まで")] public string UserName { get{ return this._userName; } set { if((object.ReferenceEquals(this._userName, value) != true)) { this.ValidateProperty("UserName", value); this._userName = value; this.RaisePropertyChanged("UserName"); } } } } 利用する際、検証先のコントロールは下記のように値をバインドする必要があります。 XAML側: <TextBox x:Name="textBoxUserName" Text="{Binding Phone, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" /> <dataInput:DescriptionViewer Name="DescriptionViewer1" Target="{Binding ElementName=textBoxUserName}" Description="入力必須な項目" PropertyPath="UserName" /> コード側: this.DataContext = new Users(); 「INotifyPropertyChanged」実装したクラスは、入力がある場合だけ、入力した値を検査しますので(ここの例では、入力した文字列の長さを検査します)、入力必須の項目を検証できるため、たとえば「提出」ボタンのイベントに、下記のような処理を追加する必要があります。(INotifyPropertyChanged インターフェイスの実装は INotifyPropertyChangedの実装 を参考してください。) this.textBoxUserName.GetBindingExpression(TextBox.TextProperty).UpdateSource(); ValidationSummaryコントロール †//コントロールの名前空間の宣言 xmlns:input="clr-namespace:System.Windows.Controls;assembly=System.Controls.Data.Input" //利用 <input:ValidationSummary x:Name="vsControl" /> フレッツ光が月額556円~【GMOとくとくBB】 コメント: |