我有一个TextBox
绑定到一个具有int
和[Required]
属性的[Range(1, 5)]
属性,当应用启动时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
一起使用,还是可以解决此问题?
答案 0 :(得分:2)
您可以通过在绑定中使用TargetNullValue
来解决此问题,如下所示:
<TextBox Text="{Binding Test, TargetNullValue=''}"/>
这会将TargetNullValue
设置为空字符串,这告诉绑定对于绑定源,应将一个空字符串转换为null
。
如果您使用的是普通的int
,则结果是当文本更改为空字符串时,属性将完全不会设置。如果您使用的是int?
,那么当文本更改为空字符串时,属性将设置为null
。
答案 1 :(得分:2)
尽管Keith的答案可能会解决当前的问题,但是用户可以在文本框中键入任何内容这一事实仍然带来了验证问题。字符串类型变量对于绑定TextBox.Text
更为安全。
如果要与int属性绑定,则还有其他一些控件可能更合适。由于您的验证规则仅允许1到5之间的int值,因此Slider
,ComboBox
甚至一组RadioButton
都是更好的方法。
如果您打算使用TextBox
,请处理KeyDown
事件,以防止用户输入非数字键。