上位机_WPF系列总结(WPF输入验证)
1、Xaml部分定义一个输入框作为测试;
<Grid> <StackPanel Margin="5" Orientation="Horizontal" Width="200" HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock Text="姓名:" /> <TextBox Name="NameTb" Width="100" ToolTip="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"> <TextBox.Text> <Binding NotifyOnValidationError="True" Path="Name" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <local:CustomValidationRule ValidateType="Name" /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </StackPanel> </Grid>
2、新定义一个静态资源,当检测到有Error的时候,输入框的边框部分进行红色展示;
<Window.Resources> <Style x:Key="basestyle" TargetType="TextBox"> <Setter Property="Background" Value="AliceBlue" /> <Style.Triggers> <Trigger Property="Validation.HasError" Value="True"> <Setter Property="BorderBrush" Value="Red" /> </Trigger> </Style.Triggers> </Style> </Window.Resources>
3、定义CustomValidationRule类,写入校验规则;
public class CustomValidationRule : ValidationRule { public string ValidateType { get; set; } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { try { string valueString = value?.ToString().Trim(); if (ValidateType == "Name") { string name = valueString; if (!string.IsNullOrEmpty(name)) { string errorMessage = string.Empty; return name.Length > 5 ? new ValidationResult(false, "名称过长,名称长度不能超过5") : new ValidationResult(true, null); } } return new ValidationResult(true, null); } catch (Exception e) { return new ValidationResult(false, e.Message); } } }
4、触发效果