WPF 文本框接受 INT 但不接受 NULLABLE INT?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21793193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Textbox accept INT but not NULLABLE INT?
提问by SuicideSheep
Model
模型
public int? SizeLength { get; set; }
XAML
XAML
<TextBox Text="{Binding [someViewModel].SizeLength, Mode=TwoWay}"></TextBox>
Once user try to backspaceor deletethe value in this textbox, a message Value '' cannot be converted.
一旦用户尝试backspace或此中delete的值textbox,一条消息Value '' cannot be converted。
May I know what's wrong with it?
我可以知道它有什么问题吗?
回答by
Use:
用:
{Binding TargetNullValue=''}
回答by elios264
Since the integrated converters from string to single/double/int of WPF are expecting a string to parse they won't default the null value to 0 because you won't always want that behavior, so as it is written in MSDN :
由于从 WPF 的 string 到 single/double/int 的集成转换器期望一个字符串来解析,因此它们不会将 null 值默认为 0,因为您不会总是想要这种行为,因此它是在 MSDN 中编写的:
Gets or sets the value that is used in the target when the value of the source is null.
获取或设置当源的值为空时在目标中使用的值。
you use this to define your default value for null input:
您可以使用它来定义空输入的默认值:
{Binding TargetNullValue=''}
回答by Andre Mendonca
You need to add a reference of mscorlib in your XAML, Nullable or ? in your prop and use TargetNullValue with value "" like Elios said.
您需要在 XAML、Nullable 或 ? 在你的道具中,并像 Elios 所说的那样使用值为 "" 的 TargetNullValue 。
xmlns:sys="clr-namespace:System;assembly=mscorlib"
public Nullable<int> Prop { get; set; }
{Binding prop, TargetNullValue=''}

