一个可能更好的方法是只使用绑定组中的值,而不是模型。这支持绑定事务提交/中止为您的窗口定义一个绑定组
<Window.BindingGroup>
<BindingGroup >
<BindingGroup.ValidationRules>
<local:YourValidationClass/>
</BindingGroup.ValidationRules>
</BindingGroup>
</Window.BindingGroup>
YourValidationClass 应该处理 BindingGroup 的验证,而不是单个值。重要的是在这里始终使用来自 BindingGroup 的 GetValue,而不是来自模型,模型尚未修改
public class YourValidationClass : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
BindingGroup bindingGroup = (BindingGroup)value;
if (bindingGroup.Items.Count == 1)
{
User user = (User)bindingGroup.Items[0];
string firstName = (string)bindingGroup.GetValue(user, "FirstName");
string lastName = (string)bindingGroup.GetValue(user, "LastName");
if (string.IsNullOrWhiteSpace(firstName) || string.IsNullOrWhiteSpace(lastName))
{
return new ValidationResult(false, "Both fields required");
}
}
return ValidationResult.ValidResult;
}
}
然后,您的取消按钮应执行以下代码:
this.BindingGroup.CancelEdit();
你的保存按钮至少应该做
this.BindingGroup.CommitEdit();
将组值绑定到模型。