ValidationRule for WPF Textbox

前端 未结 1 1195
醉梦人生
醉梦人生 2020-12-31 17:55

I am newbie to WPF.In my UserControl,I have 8 labels and its respective 8 textboxes as follows:

1.Label : abc   2.Label : def
  TextBox1 :        TextBox2 :
         


        
1条回答
  •  北海茫月
    2020-12-31 18:14

    Why not have one ValidationRule implementation, with a property exposing what the field should end with, e.g:

    public class EndsWithValidationRule : ValidationRule
    {
        public string MustEndWith { get; set; }
    
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var str = value as string;
            if(str == null)
            {
                return new ValidationResult(false, "Please enter some text");
            }
            if(!str.EndsWith(MustEndWith))
            {
                return new ValidationResult(false, String.Format("Text must end with '{0}'", MustEndWith));
            }
            return new ValidationResult(true, null);
    
        }
    }
    

    Then you can use this like so:

    
        
            
                
                    
                
            
        
    
    
    
        
            
                
                    
                
            
        
    
    

    0 讨论(0)
提交回复
热议问题