我有一个包含文本框的用户控件。我有一个名为 Person 的类,它实现了 IDataErrorInfo 接口:
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);
}
}
鉴于此代码,绑定工作正常,但验证永远不会被触发。这段代码有什么问题?