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. <Grid.Resources>  
  2.     <!--回顾下样式的用法-->  
  3.     <Style x:Key="TextBoxStyle" TargetType="TextBox">  
  4.         <Setter Property="FontSize" Value="22"/>  
  5.         <Setter Property="HorizontalAlignment" Value="Stretch"/>  
  6.         <Setter Property="VerticalAlignment" Value="Center"/>  
  7.         <Setter Property="Width" Value="300"/>  
  8.         <Setter Property="Height" Value="50"/>  
  9.         <EventSetter Event="TextBox.GotFocus" Handler="TextBox_GotFocus"/>  
  10.           
  11.     <Style x:Key="TextBlockStyle" TargetType="TextBlock">  
  12.         <Setter Property="FontSize" Value="20"/>  
  13.         <Setter Property="HorizontalAlignment" Value="Left"/>  
  14.         <Setter Property="VerticalAlignment" Value="Center"/>  
  15.     </Style>  
  16. </Grid.Resources>  
绑定的模型类:
[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.           <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  3.               <TextBlock Text="住址:" Style="{StaticResource TextBlockStyle}"/>  
  4.               <TextBox Style="{StaticResource TextBoxStyle}"  Name="txtAddress"  Text="{Binding Address}"/>  
  5.           </StackPanel>  
  6.           <!--后台验证的错误信息在此显示-->  
  7.           <TextBlock Height="31" HorizontalAlignment="Left" Name="txtAddressHint" Foreground="Red" FontSize="14" VerticalAlignment="Top" Width="392" />  
  8.             
  9.           <Button Content="验 证" 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.       }  
当不输入任何内容时,点击按钮后,效果图:

当然这样使用还是不够简单,需要在后台写代码,显然做这种常规的验证这样用就不怎么方便。
这里将TextBoxStyle样式补充完整,因为后面用到的错误信息需要在样式用设置的位置显示。
[csharp]  view plain  copy
  1. <Style x:Key="TextBoxStyle" TargetType="TextBox">  
  2.                 <Setter Property="FontSize" Value="22"/>  
  3.                 <Setter Property="HorizontalAlignment" Value="Stretch"/>  
  4.                 <Setter Property="VerticalAlignment" Value="Center"/>  
  5.                 <Setter Property="Width" Value="300"/>  
  6.                 <Setter Property="Height" Value="50"/>  
  7.                 <EventSetter Event="TextBox.GotFocus" Handler="TextBox_GotFocus"/>  
  8.                   
  9.                 <!--控制错误信息的显示位置-->  
  10.                 <Style.Triggers>  
  11.                     <Trigger Property="Validation.HasError" Value="true">  
  12.                         <Setter Property="Validation.ErrorTemplate">  
  13.                             <Setter.Value>  
  14.                                 <ControlTemplate>  
  15.                                     <DockPanel LastChildFill="True">  
  16.                                         <TextBlock DockPanel.Dock="Bottom" Foreground="Red" FontSize="13"  
  17.                                 Text="{Binding ElementName=errorHint, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">  
  18.                                         </TextBlock>  
  19.                                         <Border BorderBrush="Red" BorderThickness="1">  
  20.                                             <AdornedElementPlaceholder Name="errorHint" />  
  21.                                         </Border>  
  22.                                     </DockPanel>  
  23.                                 </ControlTemplate>  
  24.                             </Setter.Value>  
  25.                         </Setter>  
  26.                     </Trigger>  
  27.                 </Style.Triggers>  
  28.             </Style>  
2、通过抛异常验证
注意到,开始写的ItemModel模型类中有throw new Exception("姓名不能为空或者长度不小于6!"),就是要用到这个异常。
前台代码:以对Name字段验证为例
[csharp]  view plain  copy
  1. <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  2.                 <TextBlock Text="姓名:" Style="{StaticResource TextBlockStyle}"/>  
  3.                 <!--控件绑定抛异常验证-->  
  4.                 <TextBox Name="txtName" Style="{StaticResource TextBoxStyle}" HorizontalAlignment="Stretch">  
  5.                     <TextBox.Text>  
  6.                         <Binding Path="Name" UpdateSourceTrigger="LostFocus">  
  7.                             <Binding.ValidationRules>  
  8.                                 <ExceptionValidationRule/>  
  9.                             </Binding.ValidationRules>  
  10.                         </Binding>  
  11.                     </TextBox.Text>  
  12.                 </TextBox>  
  13.             </StackPanel>  
我们看到这里用到了
[csharp]  view plain  copy
  1. <Binding.ValidationRules>  
  2.        <ExceptionValidationRule/>  
  3.    </Binding.ValidationRules>  
就是通过这个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.             <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  3.                 <TextBlock Text="其他:" Style="{StaticResource TextBlockStyle}"/>  
  4.                 <TextBox Style="{StaticResource TextBoxStyle}"  Name="txtOther">  
  5.                     <TextBox.Text>  
  6.                         <Binding Path="Other" UpdateSourceTrigger="LostFocus">  
  7.                             <Binding.ValidationRules>  
  8.                                 <local:IsNullValidateRule2  ErrorMessage="不能为空或长度不小于20"/>  
  9.                             </Binding.ValidationRules>  
  10.                         </Binding>  
  11.                     </TextBox.Text>  
  12.                 </TextBox>  
  13.             </StackPanel>  
不输入任何内容,txtOther失去焦点后,效果图:

 下面是本文工程的所有类:

 验证规则类:
[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.  <Window x:Class="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.     <Grid>  
  7.         <Grid.Resources>  
  8.             <!--回顾下样式的用法-->  
  9.             <Style x:Key="TextBoxStyle" TargetType="TextBox">  
  10.                 <Setter Property="FontSize" Value="22"/>  
  11.                 <Setter Property="HorizontalAlignment" Value="Stretch"/>  
  12.                 <Setter Property="VerticalAlignment" Value="Center"/>  
  13.                 <Setter Property="Width" Value="300"/>  
  14.                 <Setter Property="Height" Value="50"/>  
  15.                 <EventSetter Event="TextBox.GotFocus" Handler="TextBox_GotFocus"/>  
  16.                   
  17.                 <!--控制错误信息的显示位置-->  
  18.                 <Style.Triggers>  
  19.                     <Trigger Property="Validation.HasError" Value="true">  
  20.                         <Setter Property="Validation.ErrorTemplate">  
  21.                             <Setter.Value>  
  22.                                 <ControlTemplate>  
  23.                                     <DockPanel LastChildFill="True">  
  24.                                         <TextBlock DockPanel.Dock="Bottom" Foreground="Red" FontSize="13"  
  25.                                 Text="{Binding ElementName=errorHint, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">  
  26.                                         </TextBlock>  
  27.                                         <Border BorderBrush="Red" BorderThickness="1">  
  28.                                             <AdornedElementPlaceholder Name="errorHint" />  
  29.                                         </Border>  
  30.                                     </DockPanel>  
  31.                                 </ControlTemplate>  
  32.                             </Setter.Value>  
  33.                         </Setter>  
  34.                     </Trigger>  
  35.                 </Style.Triggers>  
  36.             </Style>  
  37.   
  38.   
  39.             <Style x:Key="TextBlockStyle" TargetType="TextBlock">  
  40.                 <Setter Property="FontSize" Value="20"/>  
  41.                 <Setter Property="HorizontalAlignment" Value="Left"/>  
  42.                 <Setter Property="VerticalAlignment" Value="Center"/>  
  43.             </Style>  
  44.               
  45.         </Grid.Resources>  
  46.         <StackPanel Orientation="Vertical" HorizontalAlignment="Center">  
  47.             <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  48.                 <TextBlock Text="姓名:" Style="{StaticResource TextBlockStyle}"/>  
  49.                 <!--控件绑定抛异常验证-->  
  50.                 <TextBox Name="txtName" Style="{StaticResource TextBoxStyle}" HorizontalAlignment="Stretch">  
  51.                     <TextBox.Text>  
  52.                         <Binding Path="Name" UpdateSourceTrigger="LostFocus">  
  53.                             <Binding.ValidationRules>  
  54.                                 <ExceptionValidationRule/>  
  55.                             </Binding.ValidationRules>  
  56.                         </Binding>  
  57.                     </TextBox.Text>  
  58.                 </TextBox>  
  59.             </StackPanel>  
  60.             <TextBlock Height="31" HorizontalAlignment="Left" Name="txtNameHint" Foreground="Red" FontSize="14" VerticalAlignment="Top" Width="392" />  
  61.               
  62.             <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  63.                 <TextBlock Text="年龄:" Style="{StaticResource TextBlockStyle}" />  
  64.                 <!--控件绑定抛异常验证-->  
  65.                 <TextBox Name="txtAge" Style="{StaticResource TextBoxStyle}" HorizontalAlignment="Stretch">  
  66.                     <TextBox.Text>  
  67.                         <Binding Path="Age" UpdateSourceTrigger="LostFocus">  
  68.                             <Binding.ValidationRules>  
  69.                                 <ExceptionValidationRule/>  
  70.                             </Binding.ValidationRules>  
  71.                         </Binding>  
  72.                     </TextBox.Text>  
  73.                 </TextBox>  
  74.             </StackPanel>  
  75.             <TextBlock Height="31" HorizontalAlignment="Left" Name="txtAgeHint" Foreground="Red" FontSize="14" VerticalAlignment="Top" Width="392" />  
  76.               
  77.             <!--后台调用方法验证-->  
  78.             <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  79.                 <TextBlock Text="住址:" Style="{StaticResource TextBlockStyle}"/>  
  80.                 <TextBox Style="{StaticResource TextBoxStyle}"  Name="txtAddress"  Text="{Binding Address}"/>  
  81.             </StackPanel>  
  82.             <!--后台验证的错误信息在此显示-->  
  83.             <TextBlock Height="31" HorizontalAlignment="Left" Name="txtAddressHint" Foreground="Red" FontSize="14" VerticalAlignment="Top" Width="392" />  
  84.               
  85.             <!--控件绑定使用验证规则类进行验证-->  
  86.             <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">  
  87.                 <TextBlock Text="其他:" Style="{StaticResource TextBlockStyle}"/>  
  88.                 <TextBox Style="{StaticResource TextBoxStyle}"  Name="txtOther">  
  89.                     <TextBox.Text>  
  90.                         <Binding Path="Other" UpdateSourceTrigger="LostFocus">  
  91.                             <Binding.ValidationRules>  
  92.                                 <local:IsNullValidateRule2  ErrorMessage="不能为空或长度不小于20"/>  
  93.                             </Binding.ValidationRules>  
  94.                         </Binding>  
  95.                     </TextBox.Text>  
  96.                 </TextBox>  
  97.             </StackPanel>  
  98.               
  99.             <Button Content="验 证" Height="36" FontSize="18" HorizontalAlignment="Center" Name="button1" VerticalAlignment="Center" Width="124"   
  100.                         Click="button1_Click"  Margin="0,30,0,0"/>  
  101.         </StackPanel>  
  102.     </Grid>  
  103. </Window>  
后台:
[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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值