我在我的模型上实现了INotifyDataErrorInfo。但我似乎无法在需要时使用它。例如。它不应该在启动时或我正在键入时验证错误。仅在单击按钮时(保存)。
我目前在我的XAML中有这个:
<TextBox Text="{Binding Car.Model, ValidatesOnNotifyDataErrors=False, UpdateSourceTrigger=Explicit}"/>
在SaveCommand下的ViewModel中:
Car.Validate();
if (Car.HasErrors)
{
return;
}
//else save
我的模型看起来像这样:
Public class Car:ValidateModelBase
{
private string _model;
[Required (ErrorMessage ="This field is required")]
public string Model
{
get { return _model; }
set { _model= value; RaisePropertyChanged(); }
}
}
然后我执行ValidateModelBase:
public class ValidateModelBase: INotifyDataErrorInfo, INotifyPropertyChanged
{
private ConcurrentDictionary<string, List<string>> _errors =
new ConcurrentDictionary<string, List<string>>();
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName]string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
ValidateAsync();
}
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public void OnErrorsChanged(string propertyName)
{
var handler = ErrorsChanged;
if (handler != null)
handler(this, new DataErrorsChangedEventArgs(propertyName));
}
public IEnumerable GetErrors(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
{
return null;
}
List<string> errorsForName;
_errors.TryGetValue(propertyName, out errorsForName);
return errorsForName;
}
public bool HasErrors
{
get { return _errors.Any(kv => kv.Value != null && kv.Value.Count > 0); }
}
public Task ValidateAsync()
{
return Task.Run(() => Validate());
}
private object _lock = new object();
public void Validate()
{
lock (_lock)
{
var validationContext = new ValidationContext(this, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(this, validationContext, validationResults, true);
foreach (var kv in _errors.ToList())
{
if (validationResults.All(r => r.MemberNames.All(m => m != kv.Key)))
{
List<string> outLi;
_errors.TryRemove(kv.Key, out outLi);
OnErrorsChanged(kv.Key);
}
}
var q = from r in validationResults
from m in r.MemberNames
group r by m into g
select g;
foreach (var prop in q)
{
var messages = prop.Select(r => r.ErrorMessage).ToList();
if (_errors.ContainsKey(prop.Key))
{
List<string> outLi;
_errors.TryRemove(prop.Key, out outLi);
}
_errors.TryAdd(prop.Key, messages);
OnErrorsChanged(prop.Key);
}
}
}
}
事情就是它正常工作,但是当打开Window时,文本框已经是红色的。我希望它在启动时忽略验证,仅在我单击“保存”时验证。单击“保存”时,它将验证并查看是否存在任何错误。出现错误时,将设置验证(现在应将其标记为红色)并且窗口保持打开状态。我怎样才能做到这一点。
答案 0 :(得分:0)
如果您的模型只应在保存时进行验证,我会建立您的模型工具IEditableObject
并确保在进行更改之前调用BeginEdit
,并在提交之前调用EndEdit
变化(即保存)。
让您的基类跟踪它是否处于编辑模式&#39;,如果是,则禁止任何验证。调用EndEdit
后,再次允许验证并触发ErrorsChanged
。由您来决定如何处理CancelEdit
。
某些控件(如数据网格)具有对IEditableObject
的内置支持,并在您开始编辑行时调用BeginEdit
,在提交行时调用EndEdit
。这是一个非常有用的界面。