以下内容适合像我一样的新手!有什么好的建议!还望大家指点!
效果图如下:
第一步:先 新建文件夹 CheckValueLibrary 在新建一个类 PhoneNumberCheck 用于验证 此类继承 ValidationRule 类!
PhoneNumberCheck 类代码如下(正则表达式有错,可借鉴方法):
- <span style="font-size:14px;">namespace Demo1.CheckValueLibrary
- {
- //
- public class PhoneNumberCheck<span style="color:#ff6600;">:ValidationRule</span>
- {
- public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
- {
- string PoneNumber = value.ToString();
- bool rt= Regex.IsMatch(PoneNumber, "^[0-9]*$");// 正则表达式(验证是否为数字)
- if (!rt || PoneNumber.Length > 11)
- {
- return new ValidationResult(false,"请输入正确的电话号码");
- }
- else
- {
- return new ValidationResult(true, null);
- }
- }
- }
- }</span>
第三步:自定义错误提示模板样式,代码如下:
- <span style="font-size:14px;"><Window.Resources>
- <Style TargetType="TextBox">
- <!--错误模板-->
- <Setter Property="Validation.ErrorTemplate">
- <Setter.Value>
- <ControlTemplate>
- <Border CornerRadius="3" BorderBrush="Red" BorderThickness="1">
- <!-- 若错误提示现在 在下方 去掉 Orientation="Horizontal" 即可 -->
- <StackPanel Orientation="Horizontal">
- <AdornedElementPlaceholder x:Name="Adorned"/>
- <TextBlock Width="{TemplateBinding Width}" Foreground="Red">
- <!--显示错误提示内容-->
- <TextBlock.Text>
- <Binding ElementName="Adorned"
- Path="AdornedElement.(Validation.Errors)[0].ErrorContent"/>
- </TextBlock.Text>
- <!--错误提示字的的样式-->
- <TextBlock.Effect>
- <DropShadowEffect Opacity="0.6" ShadowDepth="3" Color="Black"/>
- </TextBlock.Effect>
- </TextBlock>
- </StackPanel>
- </Border>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- </Style>
- </Window.Resources></span>
第四步:在TextBox中 加入验证,代码如下:
- <span style="font-size:14px;"><TextBox Margin="59,38,94,201">
- <TextBox.Text>
- <Binding Path="PhoneNumber"
- NotifyOnValidationError="True"
- UpdateSourceTrigger="PropertyChanged">
- <!--输入验证-->
- <Binding.ValidationRules>
- <CheckValue:PhoneNumberCheck></CheckValue:PhoneNumberCheck>
- </Binding.ValidationRules>
- </Binding>
- </TextBox.Text>
- </TextBox></span>