如果值是 Nullable,则绑定(bind)不起作用,但如果不是,则绑定(bind)就像一个魅力。
XAML
<TextBox
Text="{Binding Age, Mode=TwoWay, TargetNullValue=''}"
InputScope="Number"
MaxLength="2"/>
怎么了?
最佳答案
Mikko 促使我找到了解决方案。因此,值必须以目标类型从转换器返回。 "23"
不是有效的 int?
,它不会自动转换。你应该自己做。
在我的特殊情况下,这个转换器帮助了我:
转换器
public class NullableIntToString : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (value == null || string.IsNullOrWhiteSpace(value.ToString())) return null;
int result;
if (int.TryParse(value.ToString(), out result)) return result;
return null;
}
}
XAML
<...>
<Page.Resources>
<converters:NullableIntToString x:Key="NullableValue"/>
</Page.Resources>
<...>
<TextBox
Text="{
Binding Age,
Mode=TwoWay,
Converter={StaticResource NullableValue}
}"
InputScope="Number"
MaxLength="2"/>
<...>
关于c# - Windows Phone 可为空的 int 绑定(bind)不适用于 TextBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25040049/