当用到输入框时,验证肯定就要用到。一般这样可以在后台写方法,然后将错误信息显示到某个控件上。当然比如做一些不能为空,不能是某种字符的一般性验证时还是用自带的验证类会比较方便一些。下面就看看ValidationRule在做常规验证时的用法。用法很简单就是定义一个类继承ValidationRule,然后实现Validate即可。如下:
那么主要看在界面上如何使用呢。为了方便起见,先把本文需要用到的样式、要绑定的模型类什么的先写好。
样式(TextBoxStyle样式,还有一部分等后面用到了再补充):
绑定的模型类:
1、在后台调用,前台用控件显示错误信息。
前台代码:
这是其实就是在button1_Click进行验证,并把错误信息显示在txtAddressHint上。
后台代码:
当不输入任何内容时,点击按钮后,效果图:
当然这样使用还是不够简单,需要在后台写代码,显然做这种常规的验证这样用就不怎么方便。
这里将TextBoxStyle样式补充完整,因为后面用到的错误信息需要在样式用设置的位置显示。
2、通过抛异常验证
注意到,开始写的ItemModel模型类中有throw new Exception("姓名不能为空或者长度不小于6!"),就是要用到这个异常。
前台代码:以对Name字段验证为例
我们看到这里用到了
就是通过这个ExceptionValidationRule异常来进行显示错误信息。
不需要在后台写代码了,当没有输入任何内容时,txtName失去焦点后效果图:
3、绑定验证规则类进行验证
也可以直接绑定验证规则的类,进行验证。
验证规则类:
前台代码:
不输入任何内容,txtOther失去焦点后,效果图:
下面是本文工程的所有类:
验证规则类:
绑定的类:
主界面:
后台:
注意这里TextBox_GotFocus事件,主要是为了触发绑定类的赋值,然后才能进行验证。
当然也不是说,使用控件在后台控制错误信息就不能用了,在有些场合ValidationRule验证也是不合适用的,还是要用到后台判断进行显示信息的。
- public class IsNullValidateRule1 : ValidationRule
- {
- public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
- {
- if (value == null)
- {
- return new ValidationResult(false, "不能为空!");
- }
- string valuestr = value.ToString();
- if (valuestr.Count() < 6)
- {
- return new ValidationResult(false, "输入内容长度不小于10!");
- }
- return ValidationResult.ValidResult;
- }
- }
样式(TextBoxStyle样式,还有一部分等后面用到了再补充):
- <Grid.Resources>
- <!--回顾下样式的用法-->
- <Style x:Key="TextBoxStyle" TargetType="TextBox">
- <Setter Property="FontSize" Value="22"/>
- <Setter Property="HorizontalAlignment" Value="Stretch"/>
- <Setter Property="VerticalAlignment" Value="Center"/>
- <Setter Property="Width" Value="300"/>
- <Setter Property="Height" Value="50"/>
- <EventSetter Event="TextBox.GotFocus" Handler="TextBox_GotFocus"/>
- <Style x:Key="TextBlockStyle" TargetType="TextBlock">
- <Setter Property="FontSize" Value="20"/>
- <Setter Property="HorizontalAlignment" Value="Left"/>
- <Setter Property="VerticalAlignment" Value="Center"/>
- </Style>
- </Grid.Resources>
- public class NotifyProperty : INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler PropertyChanged;
- public void OnPropertyChanged(string propertyname)
- {
- if (this.PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
- }
- }
- }
- public class ItemModel : NotifyProperty
- {
- private string name = string.Empty;
- private int? age ;
- private string address = string.Empty;
- private string other = string.Empty;
- public string Name
- {
- get { return this.name; }
- set
- {
- this.name = value;
- this.OnPropertyChanged("Name");
- if (string.IsNullOrEmpty(value) || value.Count() < 6)
- {
- throw new ApplicationException("姓名不能为空或者长度不小于6!");
- }
- }
- }
- public int? Age
- {
- get { return this.age; }
- set
- {
- this.age = value;
- this.OnPropertyChanged("Age");
- if (value==null || value <= 0 || value > 180)
- {
- throw new ApplicationException("请输入正确的年龄");
- }
- }
- }
- public string Address
- {
- get { return address; }
- set
- {
- address = value;
- this.OnPropertyChanged("Address");
- }
- }
- public string Other
- {
- get { return other; }
- set
- {
- other = value;
- this.OnPropertyChanged("Other");
- }
- }
- }
前台代码:
- <!--后台调用方法验证-->
- <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">
- <TextBlock Text="住址:" Style="{StaticResource TextBlockStyle}"/>
- <TextBox Style="{StaticResource TextBoxStyle}" Name="txtAddress" Text="{Binding Address}"/>
- </StackPanel>
- <!--后台验证的错误信息在此显示-->
- <TextBlock Height="31" HorizontalAlignment="Left" Name="txtAddressHint" Foreground="Red" FontSize="14" VerticalAlignment="Top" Width="392" />
- <Button Content="验 证" Height="36" FontSize="18" HorizontalAlignment="Center" Name="button1" VerticalAlignment="Center" Width="124"
- Click="button1_Click" Margin="0,30,0,0"/>
后台代码:
- private void button1_Click(object sender, RoutedEventArgs e)
- {
- IsNullValidateRule1 isnullRule = new IsNullValidateRule1();
- ValidationResult result = isnullRule.Validate(this.txtAddress.Text, null);
- if (!result.IsValid)
- {
- this.txtAddressHint.Text = result.ErrorContent.ToString();
- return;
- }
- }
当然这样使用还是不够简单,需要在后台写代码,显然做这种常规的验证这样用就不怎么方便。
这里将TextBoxStyle样式补充完整,因为后面用到的错误信息需要在样式用设置的位置显示。
- <Style x:Key="TextBoxStyle" TargetType="TextBox">
- <Setter Property="FontSize" Value="22"/>
- <Setter Property="HorizontalAlignment" Value="Stretch"/>
- <Setter Property="VerticalAlignment" Value="Center"/>
- <Setter Property="Width" Value="300"/>
- <Setter Property="Height" Value="50"/>
- <EventSetter Event="TextBox.GotFocus" Handler="TextBox_GotFocus"/>
- <!--控制错误信息的显示位置-->
- <Style.Triggers>
- <Trigger Property="Validation.HasError" Value="true">
- <Setter Property="Validation.ErrorTemplate">
- <Setter.Value>
- <ControlTemplate>
- <DockPanel LastChildFill="True">
- <TextBlock DockPanel.Dock="Bottom" Foreground="Red" FontSize="13"
- Text="{Binding ElementName=errorHint, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
- </TextBlock>
- <Border BorderBrush="Red" BorderThickness="1">
- <AdornedElementPlaceholder Name="errorHint" />
- </Border>
- </DockPanel>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- </Trigger>
- </Style.Triggers>
- </Style>
注意到,开始写的ItemModel模型类中有throw new Exception("姓名不能为空或者长度不小于6!"),就是要用到这个异常。
前台代码:以对Name字段验证为例
- <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">
- <TextBlock Text="姓名:" Style="{StaticResource TextBlockStyle}"/>
- <!--控件绑定抛异常验证-->
- <TextBox Name="txtName" Style="{StaticResource TextBoxStyle}" HorizontalAlignment="Stretch">
- <TextBox.Text>
- <Binding Path="Name" UpdateSourceTrigger="LostFocus">
- <Binding.ValidationRules>
- <ExceptionValidationRule/>
- </Binding.ValidationRules>
- </Binding>
- </TextBox.Text>
- </TextBox>
- </StackPanel>
- <Binding.ValidationRules>
- <ExceptionValidationRule/>
- </Binding.ValidationRules>
不需要在后台写代码了,当没有输入任何内容时,txtName失去焦点后效果图:
3、绑定验证规则类进行验证
也可以直接绑定验证规则的类,进行验证。
验证规则类:
- public class IsNullValidateRule2 : ValidationRule
- {
- public string ErrorMessage
- {
- get;
- set;
- }
- public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
- {
- if (value == null)
- {
- return new ValidationResult(false, ErrorMessage);
- }
- string valuestr = value.ToString();
- if (valuestr.Count() < 6)
- {
- return new ValidationResult(false, ErrorMessage);
- }
- return ValidationResult.ValidResult;
- }
- }
- <!--控件绑定使用验证规则类进行验证-->
- <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">
- <TextBlock Text="其他:" Style="{StaticResource TextBlockStyle}"/>
- <TextBox Style="{StaticResource TextBoxStyle}" Name="txtOther">
- <TextBox.Text>
- <Binding Path="Other" UpdateSourceTrigger="LostFocus">
- <Binding.ValidationRules>
- <local:IsNullValidateRule2 ErrorMessage="不能为空或长度不小于20"/>
- </Binding.ValidationRules>
- </Binding>
- </TextBox.Text>
- </TextBox>
- </StackPanel>
下面是本文工程的所有类:
验证规则类:
- public class IsNullValidateRule1 : ValidationRule
- {
- public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
- {
- if (value == null)
- {
- return new ValidationResult(false, "不能为空!");
- }
- string valuestr = value.ToString();
- if (valuestr.Count() < 6)
- {
- return new ValidationResult(false, "输入内容长度不小于10!");
- }
- return ValidationResult.ValidResult;
- }
- }
- public class IsNullValidateRule2 : ValidationRule
- {
- public string ErrorMessage
- {
- get;
- set;
- }
- public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
- {
- if (value == null)
- {
- return new ValidationResult(false, ErrorMessage);
- }
- string valuestr = value.ToString();
- if (valuestr.Count() < 6)
- {
- return new ValidationResult(false, ErrorMessage);
- }
- return ValidationResult.ValidResult;
- }
- }
- public class NotifyProperty : INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler PropertyChanged;
- public void OnPropertyChanged(string propertyname)
- {
- if (this.PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
- }
- }
- }
- public class ItemModel : NotifyProperty
- {
- private string name = string.Empty;
- private int? age ;
- private string address = string.Empty;
- private string other = string.Empty;
- public string Name
- {
- get { return this.name; }
- set
- {
- this.name = value;
- this.OnPropertyChanged("Name");
- if (string.IsNullOrEmpty(value) || value.Count() < 6)
- {
- throw new Exception("姓名不能为空或者长度不小于6!");
- }
- }
- }
- public int? Age
- {
- get { return this.age; }
- set
- {
- this.age = value;
- this.OnPropertyChanged("Age");
- if (value==null || value <= 0 || value > 180)
- {
- throw new Exception("请输入正确的年龄");
- }
- }
- }
- public string Address
- {
- get { return address; }
- set
- {
- address = value;
- this.OnPropertyChanged("Address");
- }
- }
- public string Other
- {
- get { return other; }
- set
- {
- other = value;
- this.OnPropertyChanged("Other");
- }
- }
- }
- <Window x:Class="TestValidateRule.MainWindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="clr-namespace:TestValidateRule.ValidateRules"
- Title="MainWindow" Height="510" Width="890">
- <Grid>
- <Grid.Resources>
- <!--回顾下样式的用法-->
- <Style x:Key="TextBoxStyle" TargetType="TextBox">
- <Setter Property="FontSize" Value="22"/>
- <Setter Property="HorizontalAlignment" Value="Stretch"/>
- <Setter Property="VerticalAlignment" Value="Center"/>
- <Setter Property="Width" Value="300"/>
- <Setter Property="Height" Value="50"/>
- <EventSetter Event="TextBox.GotFocus" Handler="TextBox_GotFocus"/>
- <!--控制错误信息的显示位置-->
- <Style.Triggers>
- <Trigger Property="Validation.HasError" Value="true">
- <Setter Property="Validation.ErrorTemplate">
- <Setter.Value>
- <ControlTemplate>
- <DockPanel LastChildFill="True">
- <TextBlock DockPanel.Dock="Bottom" Foreground="Red" FontSize="13"
- Text="{Binding ElementName=errorHint, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
- </TextBlock>
- <Border BorderBrush="Red" BorderThickness="1">
- <AdornedElementPlaceholder Name="errorHint" />
- </Border>
- </DockPanel>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- </Trigger>
- </Style.Triggers>
- </Style>
- <Style x:Key="TextBlockStyle" TargetType="TextBlock">
- <Setter Property="FontSize" Value="20"/>
- <Setter Property="HorizontalAlignment" Value="Left"/>
- <Setter Property="VerticalAlignment" Value="Center"/>
- </Style>
- </Grid.Resources>
- <StackPanel Orientation="Vertical" HorizontalAlignment="Center">
- <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">
- <TextBlock Text="姓名:" Style="{StaticResource TextBlockStyle}"/>
- <!--控件绑定抛异常验证-->
- <TextBox Name="txtName" Style="{StaticResource TextBoxStyle}" HorizontalAlignment="Stretch">
- <TextBox.Text>
- <Binding Path="Name" UpdateSourceTrigger="LostFocus">
- <Binding.ValidationRules>
- <ExceptionValidationRule/>
- </Binding.ValidationRules>
- </Binding>
- </TextBox.Text>
- </TextBox>
- </StackPanel>
- <TextBlock Height="31" HorizontalAlignment="Left" Name="txtNameHint" Foreground="Red" FontSize="14" VerticalAlignment="Top" Width="392" />
- <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">
- <TextBlock Text="年龄:" Style="{StaticResource TextBlockStyle}" />
- <!--控件绑定抛异常验证-->
- <TextBox Name="txtAge" Style="{StaticResource TextBoxStyle}" HorizontalAlignment="Stretch">
- <TextBox.Text>
- <Binding Path="Age" UpdateSourceTrigger="LostFocus">
- <Binding.ValidationRules>
- <ExceptionValidationRule/>
- </Binding.ValidationRules>
- </Binding>
- </TextBox.Text>
- </TextBox>
- </StackPanel>
- <TextBlock Height="31" HorizontalAlignment="Left" Name="txtAgeHint" Foreground="Red" FontSize="14" VerticalAlignment="Top" Width="392" />
- <!--后台调用方法验证-->
- <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">
- <TextBlock Text="住址:" Style="{StaticResource TextBlockStyle}"/>
- <TextBox Style="{StaticResource TextBoxStyle}" Name="txtAddress" Text="{Binding Address}"/>
- </StackPanel>
- <!--后台验证的错误信息在此显示-->
- <TextBlock Height="31" HorizontalAlignment="Left" Name="txtAddressHint" Foreground="Red" FontSize="14" VerticalAlignment="Top" Width="392" />
- <!--控件绑定使用验证规则类进行验证-->
- <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="0,20,0,5">
- <TextBlock Text="其他:" Style="{StaticResource TextBlockStyle}"/>
- <TextBox Style="{StaticResource TextBoxStyle}" Name="txtOther">
- <TextBox.Text>
- <Binding Path="Other" UpdateSourceTrigger="LostFocus">
- <Binding.ValidationRules>
- <local:IsNullValidateRule2 ErrorMessage="不能为空或长度不小于20"/>
- </Binding.ValidationRules>
- </Binding>
- </TextBox.Text>
- </TextBox>
- </StackPanel>
- <Button Content="验 证" Height="36" FontSize="18" HorizontalAlignment="Center" Name="button1" VerticalAlignment="Center" Width="124"
- Click="button1_Click" Margin="0,30,0,0"/>
- </StackPanel>
- </Grid>
- </Window>
- public partial class MainWindow : Window
- {
- private ItemModel model = new ItemModel();
- public MainWindow()
- {
- InitializeComponent();
- this.DataContext = model;
- }
- private void button1_Click(object sender, RoutedEventArgs e)
- {
- IsNullValidateRule1 isnullRule = new IsNullValidateRule1();
- ValidationResult result = isnullRule.Validate(this.txtAddress.Text, null);
- if (!result.IsValid)
- {
- this.txtAddressHint.Text = result.ErrorContent.ToString();
- return;
- }
- }
- void TextBox_GotFocus(object sender, EventArgs e)
- {
- TextBox tb = sender as TextBox;
- if (tb != null)
- {
- tb.Text = tb.Text;
- }
- }
- }
当然也不是说,使用控件在后台控制错误信息就不能用了,在有些场合ValidationRule验证也是不合适用的,还是要用到后台判断进行显示信息的。
详细代码下载:http://download.csdn.net/detail/yysyangyangyangshan/5480153