WPF中TextBox的自动验证:
演示 :
用以下两个TextBox分别显示验证IP和非空值验证,先看效果:
IP自动验证效果:
非空值自动验证效果:
第一步:定义TextBox验证的样式:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Style x:Key="ValidationTextBoxStyle" TargetType="{x:Type TextBox}"> <Setter Property="Validation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <DockPanel LastChildFill="True"> <TextBlock DockPanel.Dock="Right" Foreground="Red" FontSize="14" FontWeight="Bold" ToolTip="{Binding ElementName=adornerPlaceholder, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"> * </TextBlock> <Border BorderBrush="Red" BorderThickness="1" CornerRadius="3"> <AdornedElementPlaceholder Name="adornerPlaceholder"></AdornedElementPlaceholder> </Border> </DockPanel> </ControlTemplate> </Setter.Value> </Setter> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </Style.Triggers> </Style> </ResourceDictionary>
第二步:绑定上面的样式:
<TextBox x:Name="TxDataBaseIP" Style="{DynamicResource ValidationTextBoxStyle}" ..... <TextBox x:Name="TbDataBaseAcount" Style="{DynamicResource ValidationTextBoxStyle}" ......
第三步:为Text的Text属性定义和添加验证规则:
定义验证规则:
using System.Text.RegularExpressions; using System.Windows.Controls; namespace NCS.Client.WPF.Resources.Validations { public class NotNullValidationRule : ValidationRule { public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { if (string.IsNullOrEmpty(value as string) || string.IsNullOrWhiteSpace(value as string)) { return new ValidationResult(false, "不能为空!"); } return new ValidationResult(true, null); } } public class IPAddressRule : ValidationRule { public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { string IPAddress = value as string; if (!string.IsNullOrWhiteSpace(IPAddress)) { string IPAddressFormartRegex = @"^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$"; // 检查输入的字符串是否符合IP地址格式 if (!Regex.IsMatch(IPAddress, IPAddressFormartRegex)) { return new ValidationResult(false, "IP地址格式不正确"); } } return new ValidationResult(true, null); } } }
绑定规则:
<TextBox.Text>
<Binding Path="DataBaseIp" Mode="TwoWay"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<validations:IPAddressRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<TextBox.Text> <Binding Path="DataBaseAccount" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <validations:NotNullValidationRule/> </Binding.ValidationRules> </Binding> </TextBox.Text>
完整的控件xaml代码:
<StackPanel Orientation="Horizontal" Height="30" VerticalAlignment="Top"> <TextBlock Text="数 据 库 IP" Width="70" VerticalAlignment="Center"/> <TextBox x:Name="TxDataBaseIP" Style="{DynamicResource ValidationTextBoxStyle}" MaxWidth="150" Width="150" Height="25" HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBox.Text> <Binding Path="DataBaseIp" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <validations:IPAddressRule/> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </StackPanel> <StackPanel Orientation="Horizontal" Height="35" VerticalAlignment="Top"> <TextBlock Text="数据库账户" Width="70" VerticalAlignment="Center"/> <TextBox x:Name="TbDataBaseAcount" Style="{DynamicResource ValidationTextBoxStyle}" MaxWidth="150" Width="150" Height="25" HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBox.Text> <Binding Path="DataBaseAccount" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <validations:NotNullValidationRule/> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </StackPanel>
【the end】
后记:
1.有个缺陷的:一开始初始化界面的时候没有进行验证,必须是输入一次,以后才进行验证。如下图所示:
2. 上面的文章描述是基于我的一个实际项目编写的,有网友可能需要源码,现在我从原来的项目中剥离出这部分知识的代码部分,所以下载到的源码与上述的代码的
命名空间不一致。
源码下载:
链接:http://pan.baidu.com/s/1jGE9V0q 密码:05g3
拓展学习:
Regex Validation in WPF
http://www.codeproject.com/Articles/15610/Regex-Validation-in-WPF