WPF新手之验证器及验证出错模板

首先要定义一个实现了ValidationRule接口的验证器类:

public class IPAddressValidationRule : ValidationRule { public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { string ip = value.ToString(); try { System.Diagnostics.Debug.WriteLine(ip); IPAddress IP = IPAddress.Parse(ip); System.Diagnostics.Debug.WriteLine(IP); return new ValidationResult(true, null); } catch (ArgumentNullException) { return new ValidationResult(false, "地址不能为空"); } catch (FormatException) { return new ValidationResult(false, "地址格式不正确/n应该为xxx.xxx.xxx.xxx/n其中x为数字"); } } }

 

接着定义验证触发器和错误模板:

<!--验证器样式--> <Style x:Key="IPValidationStyle" TargetType="{x:Type TextBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </Style.Triggers> </Style> <!--验证器出错模板--> <ControlTemplate x:Key="validationTemplate"> <DockPanel> <TextBlock DockPanel.Dock="Right" Foreground="White" Background="Red" Text="{Binding ElementName=Adorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/> <AdornedElementPlaceholder x:Name="Adorner"/> </DockPanel> </ControlTemplate>

被验证的对象: <TextBox x:Name="IPAddressBox" Grid.Row="1" Grid.Column="1" Style="{StaticResource IPValidationStyle}" mce_Style="{StaticResource IPValidationStyle}" Validation.ErrorTemplate="{StaticResource validationTemplate}"> <TextBox.Text> <Binding Path="IP"> <Binding.ValidationRules> <local:IPAddressValidationRule/> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox>

注意:①RelativeSource.Self是指此Style的目标元素(此处即为IPAddressBox)
②(Validation.Errors)是指TextBox的验证器,但因为是附加属性,因此要加括号,以区别于TextBox自身的属性。
③出错模板中的AdornedElementPlaceholder就是指被验证的对象容器,其属性AdornedElement即为被验证的对象(此处即为IPAddressBox)。

你可能感兴趣的:(object,Path,WPF,setter,textbox,binding)