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
)提供特定于异常的消息(在我的问题中,这些消息是 FormatException
和 OverflowException
相应)。
关于wpf - 本地化 ExceptionValidationRule,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42929496/