WPF 验证之ValidationRule

 

准备一个数字验证规则类 继承ValidationRule

 1 public class NumberValidationRule : ValidationRule
 2     {
 3         private int _max = 150;
 4         private int _min = 0;
 5 
 6         /// <summary>
 7         /// 最大值
 8         /// </summary>
 9         public int Max
10         {
11             get => _max;
12             set => _max = value;
13         }
14 
15         /// <summary>
16         /// 最小值
17         /// </summary>
18         public int Min
19         {
20             get => _min;
21             set => _min = value;
22         }
23 
24         /// <summary>
25         /// 返回一个验证结果
26         /// </summary>
27         /// <param name="value">要验证的内容</param>
28         /// <param name="cultureInfo"></param>
29         /// <returns></returns>
30         public override ValidationResult Validate(object value, CultureInfo cultureInfo)
31         {
32             try
33             {
34                 var num = Convert.ToInt32(value);
35                 if (num > _max)
36                 {
37                     return new ValidationResult(false, $"年龄需要小于{_max}!");
38                 }
39                 else if (num < _min)
40                 {
41                     return new ValidationResult(false, $"年龄不能小于{_min}!");
42                 }
43                 else
44                 {
45                     return new ValidationResult(true, "");
46                 }
47             }
48             catch (FormatException)
49             {
50                 return new ValidationResult(false, "输入的不是整数");
51             }
52         }
53     }

 

然后在ViewModel里面定义属性

 1 public class PersonViewModel
 2     {
 3         public int Age { get; set; }
 4 
 5         public string EMail { get; set; }
 6 
 7         public ComboxSelectExtension<Enum, string> Genders { get; set; }
 8 
 9         public string Name { get; set; }
10 
11         public RelayCommand SaveCmd { get; set; }
12 
13         public PersonViewModel()
14         {
15             Genders = new ComboxSelectExtension<Enum, string>(AttributeHelper.GetAliases(typeof(Gender)));
16         }
17     }

Xaml里面绑定属性

 1 <TextBox
 2                     MinWidth="200"
 3                     Margin="5"
 4                     ToolTip="{Binding RelativeSource={RelativeSource Mode=Self}, Path=(Validation.Errors)[0].ErrorContent}">
 5                     <TextBox.Text>
 6                         <Binding Path="Age">
 7                             <Binding.ValidationRules>
 8                                 <v:NumberValidationRule Max="120" Min="10" />
 9                             </Binding.ValidationRules>
10                         </Binding>
11                     </TextBox.Text>
12                 </TextBox>

测试效果

 

现在给错误提示改的更醒目一点

定义一个错误提示的控件模板

 1  <!--  错误提示的控件模板  -->
 2         <ControlTemplate x:Key="ValidationTemplate">
 3             <StackPanel Orientation="Horizontal">
 4                 <!--  代表占位的控件 !关键  -->
 5                 <AdornedElementPlaceholder x:Name="adorned" />
 6                 <!--  错误提示放在这里  -->
 7                 <TextBlock
 8                     Margin="10,0,0,0"
 9                     VerticalAlignment="Center"
10                     FontSize="20"
11                     Foreground="Red"
12                     Text="{Binding ElementName=adorned, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" />
13                 <!--Text绑定到占位元素的错误提示内容上面 !关键-->
14             </StackPanel>
15         </ControlTemplate>

然后定义一个TextBox的样式

1 <Style x:Key="ValidationTextBox" TargetType="TextBox">
2             <Style.Triggers>
3                 <!--  输入有错误时候把前景色改为红色  -->
4                 <Trigger Property="Validation.HasError" Value="True">
5                     <Setter Property="Foreground" Value="Red" />
6                 </Trigger>
7             </Style.Triggers>
8         </Style>

使用样式

 1 <TextBox
 2                     MinWidth="200"
 3                     Margin="5"
 4                     Style="{StaticResource ValidationTextBox}"
 5                     Validation.ErrorTemplate="{StaticResource ValidationTemplate}">
 6                     <TextBox.Text>
 7                         <Binding Path="Age" ValidatesOnExceptions="True">
 8                             <Binding.ValidationRules>
 9                                 <v:NumberValidationRule Max="120" Min="5" />
10                             </Binding.ValidationRules>
11                         </Binding>
12                     </TextBox.Text>
13                 </TextBox>

完成效果

 

posted @ 2021-07-01 16:27  只吃肉不喝酒  阅读(216)  评论(0编辑  收藏  举报