-1

说,我有一个字段Email,我想RegEx errors在用户输入时显示。但它是一个可选字段,所以如果用户提交表单,这个字段应该清除任何错误,并且null应该发送值。

我已经INofityDataErrorInfo在我的ViewModel.

4

1 回答 1

1

如果您已经INotifyDataErrorInfo正确实现了接口,您应该能够引发ErrorsChanged事件并确保该GetErrors方法返回nullEmail属性:

...
private readonly Dictionary<string, ICollection<string>> _validationErrors = new Dictionary<string, ICollection<string>>();

public string Email { get; set; }

public void Submit()
{
    if (_validationErrors.ContainsKey(nameof(Email)))
        _validationErrors.Remove(nameof(Email));

    RaiseErrorsChanged(nameof(Email));
    ...
}

public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
private void RaiseErrorsChanged(string propertyName)
{
    if (ErrorsChanged != null)
        ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}

public System.Collections.IEnumerable GetErrors(string propertyName)
{
    if (string.IsNullOrEmpty(propertyName)
        || !_validationErrors.ContainsKey(propertyName))
        return null;

    return _validationErrors[propertyName];
}

public bool HasErrors
{
    get { return _validationErrors.Count > 0; }
}

当您引发事件GetErrors时,运行时将调用该方法。ErrorsChanged

于 2017-02-01T10:47:54.463 回答