WPF TextBox Validation

前端 未结 4 1125
日久生厌
日久生厌 2021-01-31 22:21

I have validation hooked up to a model that is bound to the TextBox container. When the window is first opened validation errors appear as the model is empty, I do

4条回答
  •  被撕碎了的回忆
    2021-01-31 22:56

    If you are implementing IDataErrorInfo, I've achieved this by checking for null values in the implementation of the validation logic. When creating a new window, checking for null will prevent your validation logic from firing. For example:

    public partial class Product : IDataErrorInfo
    {
        #region IDataErrorInfo Members
    
        public string Error
        {
            get { return null; }
        }
    
        public string this[string columnName]
        {
            get
            {
                if (columnName == "ProductName")
                {
                    // Only apply validation if there is actually a value
                    if (this.ProductName != null)
                    {
                        if (this.ProductName.Length <= 0 || this.ProductName.Length > 25)
                            return "Product Name must be between 1 and 25 characters";
                    }
                }
    
                return null;
            }
        }
    
        #endregion
    }
    

    Also, if you want to fire the validation on TextBox.LostFocus, change your binding to LostFocus, like follows:

    
    

提交回复
热议问题