Windows Phone可为空的int绑定对TextBox不起作用

本文关键字:绑定 TextBox 不起作用 int Phone Windows | 更新日期: 2023-09-27 18:15:33

如果value为空,则绑定不起作用,但如果不是,则会像符咒一样起作用。

XAML

   <TextBox 
       Text="{Binding Age, Mode=TwoWay, TargetNullValue=''}" 
       InputScope="Number" 
       MaxLength="2"/>

怎么了?

Windows Phone可为空的int绑定对TextBox不起作用

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"/>
   <...>

这个行为的一个很好的参考

不需要创建一个转换器,一个快速的解决方案是使用TargetNullValue和StringFormat 'D'

<TextBox Text="{Binding Path=Age,
               TargetNullValue={x:Static sys:String.Empty},
               StringFormat='{0:D'}}"
         InputScope="Number" />