Passing state of WPF ValidationRule to View Model in MVVM

前端 未结 9 1740
难免孤独
难免孤独 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:51

    Nirvan

    The simplest way to solve this particular issue is to use a numeric textbox, which prevents the user from entering an invalid value (you can either do this via a Third Party Vendor, or find an open source solution, such as a class derived from Textbox that suppresses non numeric input).

    The second way to handle this in MVVM without doing the above, is to define another field in you ViewModel which is a string, and bind that field to your textbox. Then, in the setter of your string field you can set the Integer, and assign a value to your numeric field:

    Here is a rough example: (NOTE I did not test it, but it should give you the idea)

    // original field
    private int _age;
    int Age 
    {
       get { return _age; }
       set { 
         _age = value; 
         RaisePropertyChanged("Age");
       }
    }
    
    
    private string _ageStr;
    string AgeStr
    {
       get { return _ageStr; }
       set { 
         _ageStr = value; 
         RaisePropertyChanged("AgeStr");
         if (!String.IsNullOrEmpty(AgeStr) && IsNumeric(AgeStr) )
             Age = intVal;
        }
    } 
    
    private bool IsNumeric(string numStr)
    {
       int intVal;
       return int.TryParse(AgeStr, out intVal);
    }
    
    #region IDataErrorInfo Members
    
        public string this[string columnName]
        {
            get
            {
    
                if (columnName == "AgeStr" && !IsNumeric(AgeStr)
                   return "Age must be numeric";
            }
        }
    
        #endregion
    

提交回复
热议问题