【问题标题】:int validation fails on empty TextBox空文本框的 int 验证失败
【发布时间】:2019-11-06 17:13:56
【问题描述】:

我有一个TextBox 绑定到具有[Required][Range(1, 5)] 属性的int 属性,当应用程序启动时TextBox 得到0,如果我按Backspace 和删除那个 0,我在调试日志中收到这条消息:

System.Windows.Data Error: 7 : ConvertBack cannot convert value '' (type 'String'). BindingExpression:Path=Order.PartyCode; DataItem='OrderVM' (HashCode=66572856); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') FormatException:'System.FormatException: Input string was not in a correct format.
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at System.String.System.IConvertible.ToInt32(IFormatProvider provider)
   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
   at MS.Internal.Data.SystemConvertConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
   at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'

并且验证不起作用。如果我使用Nullable<int> 而不是int,我会得到同样的错误!

必须拥有string 属性才能使用TextBox 还是有办法解决这个问题?

【问题讨论】:

    标签: c# wpf validation data-binding idataerrorinfo


    【解决方案1】:

    您可以通过在绑定中使用 TargetNullValue 来解决此问题,如下所示:
    <TextBox Text="{Binding Test, TargetNullValue=''}"/>

    这会将TargetNullValue 设置为一个空字符串,这告诉绑定一个空字符串应转换为绑定源的null

    如果您使用的是普通的int,结果是当文本更改为空字符串时,您的属性根本不会被设置。如果您使用的是int?,那么当文本变为空字符串时,您的属性将设置为null

    【讨论】:

    • 我不知道为什么它接受负值作为有效输入。如果没有 argetNullValue='' 验证,除了空文本框的情况外,验证效果很好。
    【解决方案2】:

    虽然 Keith 的回答可能会解决手头的问题,但用户可以在文本框中输入任何内容这一事实仍然存在验证问题。对于TextBox.Text 绑定,字符串类型变量要安全得多。

    如果您想与 int 属性绑定,还有其他控件可能更合适。由于您的验证规则只允许 1 到 5 之间的 int 值,因此 SliderComboBox 甚至一组 RadioButtons 将是更好的方法。

    如果您一心想要使用TextBox,请处理KeyDown 事件以防止用户输入非数字键。

    【讨论】:

    • 可能最好的方法是扩展TextBox 类并在那里实现KeyDown 处理程序并在需要时使用扩展的TextBox,对吧?
    • @EmonHaque:作为通用解决方案,您是对的。在他的特定情况下,这可能不需要(他只有 5 个有效值,从 1 到 5 的整数)。还值得一提的是,您建议的内容已经由 WPF Toolkit 项目实现。
    猜你喜欢
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 2014-05-05
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多