WPF ToolTip显示数据验证提示
先创建一个验证条件类继承自ValidationRule,并实现INotifyPropertyChanged进行通知提醒界面
public class ValiRange : ValidationRule , INotifyPropertyChanged
{
public string errorMessage;
public string ErrorMessage { get => errorMessage; set { errorMessage = value ; OnPropertyChanged ( "ErrorMessage" ) ; } }
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged ( string propertyname)
{
if ( this . PropertyChanged != null )
{
PropertyChanged ( this , new PropertyChangedEventArgs ( propertyname) ) ;
}
}
public override ValidationResult Validate ( object value , CultureInfo cultureInfo)
{
if ( uint . TryParse ( value . ToString ( ) , out uint result) )
{
if ( result >= 0 && result <= 64 )
{
return ValidationResult. ValidResult;
}
else
{
ErrorMessage = "请输入大于0小于64的整数!" ;
return new ValidationResult ( false , "请输入大于0小于64的整数!" ) ;
}
}
else
{
ErrorMessage = "请输入大于0小于64的整数!" ;
return new ValidationResult ( false , "请输入大于0小于64的整数!" ) ;
}
}
}
界面使用BInding并设置ToolTip显示验证器提醒
< TextBox x: Name= " txt" Width = " 120" Height = " 40" ToolTip = " {Binding ElementName=valis,Path=ErrorMessage,Mode=TwoWay}" >
< TextBox.Text>
< Binding Path = " Test.English" UpdateSourceTrigger = " PropertyChanged" > //需要将Text绑定到ViewModel属性
< Binding.ValidationRules>
< local: ValiRange x: Name= " valis" />
</ Binding.ValidationRules>
</ Binding>
</ TextBox.Text>
</ TextBox>