IDataErrorInfo:入力を検証していません
-
10-07-2019 - |
質問
テキストボックスを含むユーザーコントロールがあります。 IDataErrorInfoインターフェイスを実装するPersonというクラスがあります:
class Person : IDataErrorInfo
{
private bool hasErrors = false;
#region IDataErrorInfo Members
public string Error
{
get
{
string error = null;
if (hasErrors)
{
error = "xxThe form contains one or more validation errors";
}
return error;
}
}
public string this[string columnName]
{
get
{
return DoValidation(columnName);
}
}
#endregion
}
ユーザーコントロールは、コードがバインディングを設定するSetSourceというメソッドを公開します。
public partial class TxtUserControl : UserControl
{
private Binding _binding;
public void SetSource(string path,Object source)
{
_binding = new Binding(path);
_binding.Source = source;
ValidationRule rule;
rule = new DataErrorValidationRule();
rule.ValidatesOnTargetUpdated = true;
_binding.ValidationRules.Add(rule);
_binding.ValidatesOnDataErrors = true;
_binding.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
_binding.NotifyOnValidationError = true;
_binding.ValidatesOnExceptions = true;
txtNumeric.SetBinding(TextBox.TextProperty, _binding);
}
...
}
ユーザーコントロールを含むWPFウィンドウには次のコードがあります:
public SampleWindow()
{
person= new Person();
person.Age = new Age();
person.Age.Value = 28;
numericAdmins.SetSource("Age.Value", person);
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
if(!String.IsNullOrEmpty(person.Error))
{
MessageBox.Show("Error: "+person.Error);
}
}
このコードを指定すると、バインディングは正常に機能しますが、検証はトリガーされません。このコードの何が問題になっていますか?
解決
Age
クラスは、 IDataErrorInfo
を実装する必要があります。 Person
クラスは、 Age
のプロパティを検証するよう求められません。
それがオプションではない場合、これをサポートするのに十分に拡張可能なWPFの検証システムを作成しました。 URLは次のとおりです。
ZIPには、それを説明する単語文書があります。
編集:あまり賢くなくても年齢がIDataErrorInfoを実装できる方法の1つです:
class Constraint
{
public string Message { get; set; }
public Func<bool> Validate;
public string Name { get; set; }
}
class Age : IDataErrorInfo
{
private readonly List<Constraint> _constraints = new List<Constraint>();
public string this[string columnName]
{
get
{
var constraint = _constrains.Where(c => c.Name == columnName).FirstOrDefault();
if (constraint != null)
{
if (!constraint.Validate())
{
return constraint.Message;
}
}
return string.Empty;
}
}
}
class Person
{
private Age _age;
public Person()
{
_age = new Age(
new Constraint("Value", "Value must be greater than 28", () => Age > 28);
}
}
こちらのリンクもご覧ください:
http://www.codeproject.com/KB/cs/DelegateBusinessObjects.aspx
他のヒント
別のオプションは、AgeクラスにIDataErrorInfoを実装し、Personクラスによってキャプチャされる必要がある OnValidationRequested
のようなイベントを作成することです。これにより、Personクラスの他のプロパティに基づいてAgeフィールドを検証できます。
所属していません StackOverflow