如何处理值转换器中的异常以便可以显示自定义错误消息 [英] How to handle exception in Value converter so that custom error message can be displayed

查看:8
本文介绍了如何处理值转换器中的异常以便可以显示自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,它绑定到一个具有 Timespan 类型属性的类,并编写了一个值转换器来将字符串转换为 TimeSpan.

I have a textbox that is bound to a class with a property of type Timespan, and have written a value converter to convert a string into TimeSpan.

如果在文本框中输入了非数字,我希望显示自定义错误消息(而不是默认的输入字符串格式错误").

If a non number is entered into the textbox, I would like a custom error message to be displayed (rather than the default 'input string is in the wrong format').

转换器代码为:

    public object ConvertBack(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        try
        {
            int minutes = System.Convert.ToInt32(value);
            return new TimeSpan(0, minutes, 0);
        }
        catch
        {
            throw new FormatException("Please enter a number");
        }
    }

我在 XAML 绑定中设置了ValidatesOnExceptions=True".

I have set 'ValidatesOnExceptions=True' in the XAML binding.

但是,我遇到了以下 MSDN 文章,它解释了为什么上述方法不起作用:

However, I have come across the following MSDN article, which explains why the above will not work:

"数据绑定引擎不会捕获用户提供的转换器抛出的异常.Convert 方法抛出的任何异常,或 Convert 方法调用的方法抛出的任何未捕获异常,都被视为运行时错误"

"The data binding engine does not catch exceptions that are thrown by a user-supplied converter. Any exception that is thrown by the Convert method, or any uncaught exceptions that are thrown by methods that the Convert method calls, are treated as run-time errors"

我读过ValidatesOnExceptions 确实会在 TypeConverters 中捕获异常,所以我的具体问题是:

I have read that 'ValidatesOnExceptions does catch exceptions in TypeConverters, so my specific questions are:

  • 你什么时候会在 ValueConverter 上使用 TypeConverter
  • 假设 TypeConverter 不是上述问题的答案,我如何在 UI 中显示我的自定义错误消息

推荐答案

我会使用 ValidationRule ,这样转换器可以确保转换有效,因为只有在验证成功时才会调用它,并且您可以使用附加的属性 Validation.Errors 将包含您的 ValidationRule 在输入不是您想要的方式时创建的错误.

I would use a ValidationRule for that, this way the converter can be sure that the conversion works since it only is called if validation succeeds and you can make use of the attached property Validation.Errors which will contain the errors your ValidationRule creates if the input is not the way you want it.

例如(注意工具提示绑定)

<TextBox>
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="True">
                    <Setter Property="Background" Value="Pink"/>
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
    <TextBox.Text>
        <Binding Path="Uri">
            <Binding.ValidationRules>
                <vr:UriValidationRule />
            </Binding.ValidationRules>
            <Binding.Converter>
                <vc:UriToStringConverter />
            </Binding.Converter>
        </Binding>
    </TextBox.Text>
</TextBox>

这篇关于如何处理值转换器中的异常以便可以显示自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆