How to suppress validation when nothing is entered

前端 未结 8 1362
醉梦人生
醉梦人生 2020-12-13 04:40

I use WPF data binding with entities that implement IDataErrorInfo interface. In general my code looks like this:

Business entity:

p         


        
8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 05:05

    I believe this behavior to also be a good solution. It removes ErrorTemplate on TextBox when needed and also supports multiple "valid" invalid values (you can also improve it by making ValidInputs a dependency property).

    public class NotValidateWhenSpecified : Behavior
    {
        private ControlTemplate _errorTemplate;
    
        public string[] ValidInputs { get; set; } = { string.Empty };
    
        protected override void OnAttached()
        {
            AssociatedObject.TextChanged += HideValiationIfNecessary;
    
            _errorTemplate = Validation.GetErrorTemplate(AssociatedObject);
            Validation.SetErrorTemplate(AssociatedObject, null);
        }        
    
        protected override void OnDetaching()
        {
            AssociatedObject.TextChanged -= HideValiationIfNecessary;
        }
    
        private void HideValiationIfNecessary(object sender, TextChangedEventArgs e)
        {
            if (ValidInputs.Contains(AssociatedObject.Text))
            {                
                if (_errorTemplate != null)
                {
                    _errorTemplate = Validation.GetErrorTemplate(AssociatedObject);
                    Validation.SetErrorTemplate(AssociatedObject, null);
                }                
            }
            else
            {
                if (Validation.GetErrorTemplate(AssociatedObject) != _errorTemplate)
                {
                    Validation.SetErrorTemplate(AssociatedObject, _errorTemplate);
                }                
            }
        }
    }
    

提交回复
热议问题