日期:2014-05-17  浏览次数:20689 次

WPF,请问自定义的验证规则和转换器
WPF中,把TextBox的Text属性绑定到int型的属性上,当一个汉字不能转换的时候,文本框没有通过验证,就会出现红色边框。


如果自定义了一个数据转换器,怎么样定义转换失败的呢?,当然,转换失败的时候,肯定也就没通过验证,而且文本框也会出现红色边框。请问,这个是怎么弄的?

------解决方案--------------------
在转换类中:
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (转换成功)
return 转换值;
else
{
return new ValidationResult(false, "错误信息");
}
}

------解决方案--------------------
http://msdn.microsoft.com/zh-cn/library/vstudio/ms752347.aspx
------解决方案--------------------
嗯,我看了转换的时候没有办法报告自定义的出错信息,只能得到“xxx无法转换”这样的笼统提示信息。

要报告自定的提示信息,还是要把检查放到set property的时候,或者些自定义的ValidationRule
------解决方案--------------------
你的完整程序怎么样的?看下这个例子,出错时会有tooltip提示:

<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApp1"
    Title="" Height="400" Width="550" >
    <StackPanel>
        <StackPanel.Resources>
            <local:TestClass x:Key="test" />
            <local:ColorConverter x:Key="converter" />
            <Style TargetType="TextBox">
                <Style.Triggers>
                    <Trigger Property="Validation.HasError" Value="true">
                        <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/>