wpf - 本地化 ExceptionValidationRule

标签 wpf validation error-handling localization

绑定(bind)到 double可能会产生以下验证错误

Value ... could not be converted.


使用 ExceptionValidationRule 时错误更健谈:

Input string was not in a correct format.

Value was either too big or too small for a ...


也许还有更多。将我可以投入到绑定(bind)属性 setter 中的那些添加到他们身上。
现在,我想本地化这些消息(最好是第二个版本)。不是大惊喜,而是sources没有透露任何有用的信息(我看错地方了吗?)。
我可以制定自己的验证规则,但也许有更简单的方法?
我的问题:我可以本地化 ExceptionValidationRule ?
下面是mcve :

xml:
<TextBox>
    <TextBox.Text>
        <Binding Path="TestDouble" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <!--<local:MyValidationRule />-->
                <!--<ExceptionValidationRule />-->
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <TextBlock Margin="0,20,0,0" Foreground="Red" Text="{Binding ErrorContent}" />
        </ControlTemplate>
    </Validation.ErrorTemplate>
</TextBox>
CS:
public partial class MainWindow : Window
{
    public double TestDouble { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }
}

public class MyValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo) => ValidationResult.ValidResult; // not used

    public override ValidationResult Validate(object value, CultureInfo cultureInfo, BindingExpressionBase owner)
    {
        var bindingExpression = owner as BindingExpression;
        if (bindingExpression != null)
        {
            var type = bindingExpression.ResolvedSource.GetType().GetProperty(bindingExpression.ResolvedSourcePropertyName).PropertyType;
            if (type == typeof(double))
            {
                double result;
                if (!double.TryParse((string)value, out result))
                    return new ValidationResult(false, "The value format is not recognized"); // custom message
            }
            ... // and so on, for all types ?????
        }
        return base.Validate(value, cultureInfo, owner);
    }
}

最佳答案

要本地化在更新绑定(bind)源期间出现的此类错误消息,只需设置 UpdateSourceExceptionFilter 绑定(bind)的回调处理程序,不需要自定义验证规则(需要 ExceptionValidationRule)。

xml:

<Binding UpdateSourceExceptionFilter="ExeptionFilter" ...>

CS:
object ExeptionFilter(object bindingExpression, Exception exception)
{
    return "Localized error message";
}

显然可以是switch/case (在 C# 7 中,更早 - if/else if )提供特定于异常的消息(在我的问题中,这些消息是 FormatExceptionOverflowException 相应)。

关于wpf - 本地化 ExceptionValidationRule,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42929496/

相关文章:

wpf - 使用值转换器生成 GUI 友好的字符串是否是对值转换器的滥用?

c# - 导航到流。什么 URI(如果有的话)用于解析相对链接?

C# 正则表达式来验证日期?

javascript - 返回 false javascript 后表单仍然提交

PHP 处理 fatal error ,并将它们存储在文件中

wpf - IsMouseOver 鼠标捕获时

c# - 如何让日期选择器默认为 "Pick a Date"?

asp.net-mvc - 使用 Razor 进行表单验证

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

go - 一个go中出错关闭多个goroutine