WPF MVVM数据提交验证正确性

点击保存时,验证数据是否正确。

1.先建一个类User

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}

2.建UserViewModel

public class UserViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        private User _modelObject = new User();

        public UserViewModel(User model)
        {
            if (model != null)
            {
                _modelObject = model;
            }
        }
        public string Name
        {
            get => _modelObject.Name;
            set
            {
                _modelObject.Name = value;
                OnPropertyChanged("ID");
            }
        }

        public int Age
        {
            get => _modelObject.Age;
            set
            {
                _modelObject.Age = value;
                OnPropertyChanged("Age");
            }
        }
    }

3.建ValidationRule类

public class NotEmptyValidationRule: ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value != null)
            {
                if (value.ToString() == "")
                {
                    return new ValidationResult(false,"请输入内容");
                }
                return ValidationResult.ValidResult;
            }
            return new ValidationResult(false,"请输入内容");
        }
    }

    public class AgeValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value != null)
            {
                var flag = int.TryParse(value.ToString(), out var age);
                if (!flag)
                {
                    return new ValidationResult(false,"请输入正确的数字");
                }

                if (age > 120 || age < 0)
                {
                    return new ValidationResult(false,"请输入正确的年龄");
                }
                return ValidationResult.ValidResult;
            }
            return new ValidationResult(false,"*");
        }
    }

4.MainWindow后台

public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public UserViewModel _CurrentModel;
        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            if (!IsValidate(this)) //这里this是当前页面,如果页面有多个datacontent,应该传不同的datacontent
            {
                MessageBox.Show("数据有误,请检查页面");
                return;
            }
            MessageBox.Show("保存成功");
        }

        private void Window_Load(object sender, RoutedEventArgs e)
        {
            _CurrentModel=new UserViewModel(new User());
            this.DataContext = _CurrentModel;
        }
        
        private bool IsValidate(DependencyObject  node)
        {
            //查找页面有错误的控件
            if (node != null)
            {
                bool isValid = !Validation.GetHasError(node);
                if (!isValid)
                {
                    // If the dependency object is invalid, and it can receive the focus,
                    // set the focus
                    if (node is IInputElement) Keyboard.Focus((IInputElement)node);
                    return false;
                }
                foreach (object subnode in LogicalTreeHelper.GetChildren(node))
                {
                    if (subnode is DependencyObject)
                    {   
                        // If a child dependency object is invalid, return false immediately,
                        // otherwise keep checking
                        if (IsValidate((DependencyObject)subnode) == false) return false;
                    }
                }
                return true;
            }
            return false;
        }
    }

5.MainWindow前台


    
        
            
            
            
        
        
            
            
                
                    
                        
                            
                        
                    
                
                
                    
                
            
        
        
            
            
                
                    
                        
                    
                
                
                    
                
            
        
        
            
        
    

demo下载

你可能感兴趣的:(c#,WPF,MVVM)