【WPF 数据验证机制】二、Validation 数据验证 简单使用

上一篇:【WPF】一、WPF 数据验证机制 Validation---重要

只设计Mvvm的View层和Viewmodel层,未设计到model。下面一篇重点介绍IDataErrorInfo|INOtyfyDataErrorInfo +数据标注的联合使用,主要在model层

  1. By using Exception validation
  2. By using IDataErrorInfo
  3. By using ValidationRules
  4. By using INotifyDataErrorInfo

By Using Exception Validation

The View
<TextBox Text="{Binding StudentName, 
                ValidatesOnExceptions=True,
                UpdateSourceTrigger=PropertyChanged}" 
                VerticalAlignment="Center" 
                FontSize="20"/>
The Code behind View
namespace TestWpfValidation
{
    public partial class MainWindow : Window
    {
        private string _studentName;

        public string StudentName
        {
            get { return _studentName; }
            set
            {
                if (value.Length < 6 || value.Length > 50)
                {
                    throw new ArgumentException("Name should be between range 6-50");
                }

                _studentName = value;
            }
        }

        public MainWindow()
        {
            this.DataContext = this;
            InitializeComponent();
        }
    }
}

Output

Image 2

By Using IDataErrorInfo

The View
TextBox Text="{Binding StudentName, 
               UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" 
               VerticalAlignment="Center" 
               FontSize="20"/>
The ViewModel
public partial class MainWindow : Window, IDataErrorInfo, INotifyPropertyChanged
    {
        public MainWindow()
        {
            this.DataContext = this;
            InitializeComponent();
        }

        public string StudentName
        {
            get { return _studentName; }
            set
            {
                _studentName = value;
                OnPropertyChanged("StudentName");
            }
        }

        public string this[string columnName]
        {
            get
            {
                 switch (columnName)
            {
                case "Age":
                    if (this.Age < 10 || this.Age > 100)
                        return "The age must be between 10 and 100";
                    break;
             }
return result; } } public string Error { get { return string.Empty; } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } private string _studentName; }

By Using ValidationRules

public class StudentNameValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            string valueToValidate = value as string;
            if (valueToValidate.Length < 6 || valueToValidate.Length > 10)
            {
                return new ValidationResult(false, "Name should be between range 3-50");
            }

            return new ValidationResult(true, null);
        }
}

In XAML,

<TextBox VerticalAlignment="Center" FontSize="20"> 
      <TextBox.Text> 
       <Binding Path="StudentName" UpdateSourceTrigger="PropertyChanged"> 
            <Binding.ValidationRules> 
                 <local:StudentNameValidationRule/> 
            </Binding.ValidationRules> 
       </Binding> 
      </TextBox.Text> 
<TextBox>

Adding Style to the Error

<Style x:Key="GeneralErrorStyle">
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel>
                            <TextBlock DockPanel.Dock="Right"
                                       Foreground="Red"
                                       FontSize="12pt"
                                       Text="Error"
                                       ToolTip="{Binding ElementName=placeholder, 
                                       Path= AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
                            <AdornedElementPlaceholder x:Name="placeholder" />
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

XaML

<TextBox Style="{StaticResource GeneralErrorStyle}"
                 Text="{Binding StudentName, 
                        UpdateSourceTrigger=PropertyChanged, 
                        ValidatesOnDataErrors=True}"
                 HorizontalAlignment="Left"
                 Width="300"/>

 INotifyDataErrorInfo

接口

public interface INotifyDataErrorInfo
{
    bool HasErrors { get; }
    event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
    IEnumerable GetErrors(string propertyName);
}

Multiple errors per property

posted @ 2022-10-31 00:55  小林野夫  阅读(817)  评论(0编辑  收藏  举报
原文链接:https://www.cnblogs.com/cdaniu/