WPF:输入验证的详细用法

当用到输入框时,验证肯定就要用到。一般这样可以在后台写方法,然后将错误信息显示到某个控件上。当然比如做一些不能为空,不能是某种字符的一般性验证时还是用自带的验证类会比较方便一些。下面就看看ValidationRule在做常规验证时的用法。用法很简单就是定义一个类继承ValidationRule,然后实现Validate即可。如下:
[csharp]  view plain  copy
  1. public class IsNullValidateRule1 : ValidationRule  
  2.   {  
  3.       public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)  
  4.       {  
  5.           if (value == null)  
  6.           {  
  7.               return new ValidationResult(false"不能为空!");  
  8.           }  
  9.   
  10.   
  11.           string valuestr = value.ToString();  
  12.   
  13.   
  14.           if (valuestr.Count() < 6)  
  15.           {  
  16.               return new ValidationResult(false"输入内容长度不小于10!");  
  17.           }  
  18.   
  19.   
  20.           return ValidationResult.ValidResult;  
  21.       }  
  22.   }  
那么主要看在界面上如何使用呢。为了方便起见,先把本文需要用到的样式、要绑定的模型类什么的先写好。
样式(TextBoxStyle样式,还有一部分等后面用到了再补充):
[csharp]  view plain  copy
  1.   
  2.       
  3.     "TextBoxStyle" TargetType="TextBox">  
  4.         "FontSize" Value="22"/>  
  5.         "HorizontalAlignment" Value="Stretch"/>  
  6.         "VerticalAlignment" Value="Center"/>  
  7.         "Width" Value="300"/>  
  8.         "Height" Value="50"/>  
  9.         "TextBox.GotFocus" Handler="TextBox_GotFocus"/>  
  10.           
  11.     "TextBlockStyle" TargetType="TextBlock">  
  12.         "FontSize" Value="20"/>  
  13.         "HorizontalAlignment" Value="Left"/>  
  14.         "VerticalAlignment" Value="Center"/>  
  15.       
  16.   
绑定的模型类:
[csharp]  view plain  copy
  1. public class NotifyProperty : INotifyPropertyChanged  
  2.     {  
  3.         public event PropertyChangedEventHandler PropertyChanged;  
  4.   
  5.   
  6.         public void OnPropertyChanged(string propertyname)  
  7.         {  
  8.             if (this.PropertyChanged != null)  
  9.             {  
  10.                 PropertyChanged(thisnew PropertyChangedEventArgs(propertyname));  
  11.             }  
  12.         }  
  13.     }  
  14.       
  15.  public class ItemModel : NotifyProperty  
  16.     {  
  17.         private string name = string.Empty;  
  18.   
  19.   
  20.         private int? age ;  
  21.   
  22.   
  23.         private string address = string.Empty;  
  24.   
  25.   
  26.         private string other = string.Empty;  
  27.   
  28.   
  29.         public string Name  
  30.         {  
  31.             get { return this.name; }  
  32.   
  33.   
  34.             set  
  35.             {  
  36.                 this.name = value;  
  37.   
  38.   
  39.                 this.OnPropertyChanged("Name");  
  40.   
  41.   
  42.                 if (string.IsNullOrEmpty(value) || value.Count() < 6)  
  43.                 {  
  44.                     throw new ApplicationException("姓名不能为空或者长度不小于6!");  
  45.                 }  
  46.             }  
  47.         }  
  48.   
  49.   
  50.         public int? Age  
  51.         {  
  52.             get { return this.age; }  
  53.   
  54.   
  55.             set  
  56.             {  
  57.                 this.age = value;  
  58.   
  59.   
  60.                 this.OnPropertyChanged("Age");  
  61.   
  62.   
  63.                 if (value==null || value <= 0 || value > 180)  
  64.                 {  
  65.                     throw new ApplicationException("请输入正确的年龄");  
  66.                 }  
  67.             }  
  68.         }  
  69.   
  70.   
  71.         public string Address  
  72.         {  
  73.             get { return address; }  
  74.   
  75.   
  76.             set   
  77.             {   
  78.                 address = value;  
  79.   
  80.   
  81.                 this.OnPropertyChanged("Address");  
  82.             }  
  83.         }  
  84.   
  85.   
  86.         public string Other  
  87.         {  
  88.             get { return other; }  
  89.   
  90.   
  91.             set   
  92.             {   
  93.                 other = value;  
  94.   
  95.   
  96.                 this.OnPropertyChanged("Other");  
  97.             }  
  98.         }  
  99.     }  
1、在后台调用,前台用控件显示错误信息。
前台代码:
[csharp]  view plain  copy
  1.   
  2.           "Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  3.               "住址:" Style="{StaticResource TextBlockStyle}"/>  
  4.               "{StaticResource TextBoxStyle}"  Name="txtAddress"  Text="{Binding Address}"/>  
  5.             
  6.             
  7.           "31" HorizontalAlignment="Left" Name="txtAddressHint" Foreground="Red" FontSize="14" VerticalAlignment="Top" Width="392" />  
  8.             
  9.           "验 证" Height="36" FontSize="18" HorizontalAlignment="Center" Name="button1" VerticalAlignment="Center" Width="124"   
  10.                       Click="button1_Click"  Margin="0,30,0,0"/>  
这是其实就是在button1_Click进行验证,并把错误信息显示在txtAddressHint上。
后台代码:
[csharp]  view plain  copy
  1. private void button1_Click(object sender, RoutedEventArgs e)  
  2.       {  
  3.           IsNullValidateRule1 isnullRule = new IsNullValidateRule1();  
  4.   
  5.   
  6.           ValidationResult result = isnullRule.Validate(this.txtAddress.Text, null);  
  7.   
  8.   
  9.           if (!result.IsValid)  
  10.           {  
  11.               this.txtAddressHint.Text = result.ErrorContent.ToString();  
  12.   
  13.   
  14.               return;  
  15.           }  
  16.       }  
当不输入任何内容时,点击按钮后,效果图:
WPF:输入验证的详细用法_第1张图片
当然这样使用还是不够简单,需要在后台写代码,显然做这种常规的验证这样用就不怎么方便。
这里将TextBoxStyle样式补充完整,因为后面用到的错误信息需要在样式用设置的位置显示。
[csharp]  view plain  copy
  1. "TextBoxStyle" TargetType="TextBox">  
  2.                 "FontSize" Value="22"/>  
  3.                 "HorizontalAlignment" Value="Stretch"/>  
  4.                 "VerticalAlignment" Value="Center"/>  
  5.                 "Width" Value="300"/>  
  6.                 "Height" Value="50"/>  
  7.                 "TextBox.GotFocus" Handler="TextBox_GotFocus"/>  
  8.                   
  9.                   
  10.                   
  11.                     "Validation.HasError" Value="true">  
  12.                         "Validation.ErrorTemplate">  
  13.                               
  14.                                   
  15.                                     "True">  
  16.                                         "Bottom" Foreground="Red" FontSize="13"  
  17.                                 Text="{Binding ElementName=errorHint, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">  
  18.                                           
  19.                                         "Red" BorderThickness="1">  
  20.                                             "errorHint" />  
  21.                                           
  22.                                       
  23.                                   
  24.                               
  25.                           
  26.                       
  27.                   
  28.               
2、通过抛异常验证
注意到,开始写的ItemModel模型类中有throw new Exception("姓名不能为空或者长度不小于6!"),就是要用到这个异常。
前台代码:以对Name字段验证为例
[csharp]  view plain  copy
  1. "Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  2.                 "姓名:" Style="{StaticResource TextBlockStyle}"/>  
  3.                   
  4.                 "txtName" Style="{StaticResource TextBoxStyle}" HorizontalAlignment="Stretch">  
  5.                       
  6.                         "Name" UpdateSourceTrigger="LostFocus">  
  7.                               
  8.                                   
  9.                               
  10.                           
  11.                       
  12.                   
  13.               
我们看到这里用到了
[csharp]  view plain  copy
  1.   
  2.          
  3.      
就是通过这个ExceptionValidationRule异常来进行显示错误信息。
不需要在后台写代码了,当没有输入任何内容时,txtName失去焦点后效果图:

3、绑定验证规则类进行验证
也可以直接绑定验证规则的类,进行验证。
验证规则类:
[csharp]  view plain  copy
  1. public class IsNullValidateRule2 : ValidationRule  
  2.     {  
  3.         public string ErrorMessage  
  4.         {  
  5.             get;  
  6.   
  7.   
  8.             set;  
  9.         }  
  10.   
  11.   
  12.         public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)  
  13.         {  
  14.             if (value == null)  
  15.             {  
  16.                 return new ValidationResult(false, ErrorMessage);  
  17.             }  
  18.   
  19.   
  20.             string valuestr = value.ToString();  
  21.   
  22.   
  23.             if (valuestr.Count() < 6)  
  24.             {  
  25.                 return new ValidationResult(false, ErrorMessage);  
  26.             }  
  27.   
  28.   
  29.             return ValidationResult.ValidResult;  
  30.         }  
  31.     }  
前台代码:
[csharp]  view plain  copy
  1.   
  2.             "Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  3.                 "其他:" Style="{StaticResource TextBlockStyle}"/>  
  4.                 "{StaticResource TextBoxStyle}"  Name="txtOther">  
  5.                       
  6.                         "Other" UpdateSourceTrigger="LostFocus">  
  7.                               
  8.                                 "不能为空或长度不小于20"/>  
  9.                               
  10.                           
  11.                       
  12.                   
  13.               
不输入任何内容,txtOther失去焦点后,效果图:

 下面是本文工程的所有类:
WPF:输入验证的详细用法_第2张图片
 验证规则类:
[csharp]  view plain  copy
  1. public class IsNullValidateRule1 : ValidationRule  
  2.     {  
  3.         public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)  
  4.         {  
  5.             if (value == null)  
  6.             {  
  7.                 return new ValidationResult(false"不能为空!");  
  8.             }  
  9.   
  10.   
  11.             string valuestr = value.ToString();  
  12.   
  13.   
  14.             if (valuestr.Count() < 6)  
  15.             {  
  16.                 return new ValidationResult(false"输入内容长度不小于10!");  
  17.             }  
  18.   
  19.   
  20.             return ValidationResult.ValidResult;  
  21.         }  
  22.     }  
  23.       
  24.      public class IsNullValidateRule2 : ValidationRule  
  25.     {  
  26.         public string ErrorMessage  
  27.         {  
  28.             get;  
  29.   
  30.   
  31.             set;  
  32.         }  
  33.   
  34.   
  35.         public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)  
  36.         {  
  37.             if (value == null)  
  38.             {  
  39.                 return new ValidationResult(false, ErrorMessage);  
  40.             }  
  41.   
  42.   
  43.             string valuestr = value.ToString();  
  44.   
  45.   
  46.             if (valuestr.Count() < 6)  
  47.             {  
  48.                 return new ValidationResult(false, ErrorMessage);  
  49.             }  
  50.   
  51.   
  52.             return ValidationResult.ValidResult;  
  53.         }  
  54.     }  
 绑定的类:
[csharp]  view plain  copy
  1. public class NotifyProperty : INotifyPropertyChanged  
  2.    {  
  3.        public event PropertyChangedEventHandler PropertyChanged;  
  4.   
  5.   
  6.        public void OnPropertyChanged(string propertyname)  
  7.        {  
  8.            if (this.PropertyChanged != null)  
  9.            {  
  10.                PropertyChanged(thisnew PropertyChangedEventArgs(propertyname));  
  11.            }  
  12.        }  
  13.    }  
  14.      
  15.     public class ItemModel : NotifyProperty  
  16.    {  
  17.        private string name = string.Empty;  
  18.   
  19.   
  20.        private int? age ;  
  21.   
  22.   
  23.        private string address = string.Empty;  
  24.   
  25.   
  26.        private string other = string.Empty;  
  27.   
  28.   
  29.        public string Name  
  30.        {  
  31.            get { return this.name; }  
  32.   
  33.   
  34.            set  
  35.            {  
  36.                this.name = value;  
  37.   
  38.   
  39.                this.OnPropertyChanged("Name");  
  40.   
  41.   
  42.                if (string.IsNullOrEmpty(value) || value.Count() < 6)  
  43.                {  
  44.                    throw new Exception("姓名不能为空或者长度不小于6!");  
  45.                }  
  46.            }  
  47.        }  
  48.   
  49.   
  50.        public int? Age  
  51.        {  
  52.            get { return this.age; }  
  53.   
  54.   
  55.            set  
  56.            {  
  57.                this.age = value;  
  58.   
  59.   
  60.                this.OnPropertyChanged("Age");  
  61.   
  62.   
  63.                if (value==null || value <= 0 || value > 180)  
  64.                {  
  65.                    throw new Exception("请输入正确的年龄");  
  66.                }  
  67.            }  
  68.        }  
  69.   
  70.   
  71.        public string Address  
  72.        {  
  73.            get { return address; }  
  74.   
  75.   
  76.            set   
  77.            {   
  78.                address = value;  
  79.   
  80.   
  81.                this.OnPropertyChanged("Address");  
  82.            }  
  83.        }  
  84.   
  85.   
  86.        public string Other  
  87.        {  
  88.            get { return other; }  
  89.   
  90.   
  91.            set   
  92.            {   
  93.                other = value;  
  94.   
  95.   
  96.                this.OnPropertyChanged("Other");  
  97.            }  
  98.        }  
  99.    }  
主界面:
[csharp]  view plain  copy
  1.  "TestValidateRule.MainWindow"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         xmlns:local="clr-namespace:TestValidateRule.ValidateRules"  
  5.         Title="MainWindow" Height="510" Width="890">  
  6.       
  7.           
  8.               
  9.             "TextBoxStyle" TargetType="TextBox">  
  10.                 "FontSize" Value="22"/>  
  11.                 "HorizontalAlignment" Value="Stretch"/>  
  12.                 "VerticalAlignment" Value="Center"/>  
  13.                 "Width" Value="300"/>  
  14.                 "Height" Value="50"/>  
  15.                 "TextBox.GotFocus" Handler="TextBox_GotFocus"/>  
  16.                   
  17.                   
  18.                   
  19.                     "Validation.HasError" Value="true">  
  20.                         "Validation.ErrorTemplate">  
  21.                               
  22.                                   
  23.                                     "True">  
  24.                                         "Bottom" Foreground="Red" FontSize="13"  
  25.                                 Text="{Binding ElementName=errorHint, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">  
  26.                                           
  27.                                         "Red" BorderThickness="1">  
  28.                                             "errorHint" />  
  29.                                           
  30.                                       
  31.                                   
  32.                               
  33.                           
  34.                       
  35.                   
  36.               
  37.   
  38.   
  39.             "TextBlockStyle" TargetType="TextBlock">  
  40.                 "FontSize" Value="20"/>  
  41.                 "HorizontalAlignment" Value="Left"/>  
  42.                 "VerticalAlignment" Value="Center"/>  
  43.               
  44.               
  45.           
  46.         "Vertical" HorizontalAlignment="Center">  
  47.             "Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  48.                 "姓名:" Style="{StaticResource TextBlockStyle}"/>  
  49.                   
  50.                 "txtName" Style="{StaticResource TextBoxStyle}" HorizontalAlignment="Stretch">  
  51.                       
  52.                         "Name" UpdateSourceTrigger="LostFocus">  
  53.                               
  54.                                   
  55.                               
  56.                           
  57.                       
  58.                   
  59.               
  60.             "31" HorizontalAlignment="Left" Name="txtNameHint" Foreground="Red" FontSize="14" VerticalAlignment="Top" Width="392" />  
  61.               
  62.             "Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  63.                 "年龄:" Style="{StaticResource TextBlockStyle}" />  
  64.                   
  65.                 "txtAge" Style="{StaticResource TextBoxStyle}" HorizontalAlignment="Stretch">  
  66.                       
  67.                         "Age" UpdateSourceTrigger="LostFocus">  
  68.                               
  69.                                   
  70.                               
  71.                           
  72.                       
  73.                   
  74.               
  75.             "31" HorizontalAlignment="Left" Name="txtAgeHint" Foreground="Red" FontSize="14" VerticalAlignment="Top" Width="392" />  
  76.               
  77.               
  78.             "Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  79.                 "住址:" Style="{StaticResource TextBlockStyle}"/>  
  80.                 "{StaticResource TextBoxStyle}"  Name="txtAddress"  Text="{Binding Address}"/>  
  81.               
  82.               
  83.             "31" HorizontalAlignment="Left" Name="txtAddressHint" Foreground="Red" FontSize="14" VerticalAlignment="Top" Width="392" />  
  84.               
  85.               
  86.             "Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  87.                 "其他:" Style="{StaticResource TextBlockStyle}"/>  
  88.                 "{StaticResource TextBoxStyle}"  Name="txtOther">  
  89.                       
  90.                         "Other" UpdateSourceTrigger="LostFocus">  
  91.                               
  92.                                 "不能为空或长度不小于20"/>  
  93.                               
  94.                           
  95.                       
  96.                   
  97.               
  98.               
  99.             "验 证" Height="36" FontSize="18" HorizontalAlignment="Center" Name="button1" VerticalAlignment="Center" Width="124"   
  100.                         Click="button1_Click"  Margin="0,30,0,0"/>  
  101.           
  102.       
  103.   
后台:
[csharp]  view plain  copy
  1. public partial class MainWindow : Window  
  2.    {  
  3.        private ItemModel model = new ItemModel();  
  4.   
  5.   
  6.        public MainWindow()  
  7.        {  
  8.            InitializeComponent();  
  9.   
  10.   
  11.            this.DataContext = model;  
  12.        }  
  13.   
  14.   
  15.        private void button1_Click(object sender, RoutedEventArgs e)  
  16.        {  
  17.            IsNullValidateRule1 isnullRule = new IsNullValidateRule1();  
  18.   
  19.   
  20.            ValidationResult result = isnullRule.Validate(this.txtAddress.Text, null);  
  21.   
  22.   
  23.            if (!result.IsValid)  
  24.            {  
  25.                this.txtAddressHint.Text = result.ErrorContent.ToString();  
  26.   
  27.   
  28.                return;  
  29.            }  
  30.        }  
  31.   
  32.   
  33.        void TextBox_GotFocus(object sender, EventArgs e)  
  34.        {  
  35.            TextBox tb = sender as TextBox;  
  36.   
  37.   
  38.            if (tb != null)  
  39.            {  
  40.                tb.Text = tb.Text;  
  41.            }  
  42.        }  
  43.    }  
注意这里TextBox_GotFocus事件,主要是为了触发绑定类的赋值,然后才能进行验证。
当然也不是说,使用控件在后台控制错误信息就不能用了,在有些场合ValidationRule验证也是不合适用的,还是要用到后台判断进行显示信息的。

详细代码下载:http://download.csdn.net/detail/yysyangyangyangshan/5480153

你可能感兴趣的:(Qt)