我有一个包含文本框的用户控件。我有一个名为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
}
现在,usercontrol公开了一个名为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);
}
}
鉴于此代码,绑定工作正常,但验证永远不会被触发。这段代码怎么了?
答案 0 :(得分:3)
您的Age
课程需要实施IDataErrorInfo
。我们不会要求您的Person
课程验证Age
的属性。
如果这不是一个选项,我为WPF编写了一个可扩展的验证系统,足以支持这一点。 URL在这里:
在ZIP中是描述它的word文档。
编辑:这是年龄可以实现IDataErrorInfo而不太聪明的一种方式:
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
答案 1 :(得分:0)
另一种选择可能是在Age类上实现IDataErrorInfo,并在其上创建一个事件,如OnValidationRequested
,应由Person类捕获。这样,您可以根据Person类的其他属性验证Age字段。