Passing state of WPF ValidationRule to View Model in MVVM

前端 未结 9 1718
难免孤独
难免孤独 2021-01-01 20:10

I am stuck in a seemingly common requirement. I have a WPF Prism (for MVVM) application. My model implements the IDataErrorInfo for validation. The

9条回答
  •  时光取名叫无心
    2021-01-01 20:41

    If you provide a custom ValidationRule implementation you can store the value it received, as well as storing the last result. PseudoCode:

    public class IsInteger : ValidationRule
    {
      private int parsedValue;
    
      public IsInteger() { }
    
      public string LastValue{ get; private set; }
    
      public bool LastParseSuccesfull{ get; private set; }
    
      public int ParsedValue{ get{ return parsedValue; } }
    
      public override ValidationResult Validate( object value, CultureInfo cultureInfo )
      {
        LastValue = (string) value;
        LastParseSuccesfull = Int32.TryParse( LastValue, cultureInfo, ref parsedValue );
        return new ValidationResult( LastParseSuccesfull, LastParseSuccesfull ? "not a valid number" : null );
      }
    }
    

提交回复
热议问题