c# - Windows Phone 可为空的 int 绑定(bind)不适用于 TextBox

标签 c# wpf xaml windows-phone windows-phone-8.1

如果值是 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/

相关文章:

c# - 为什么使用 as 关键字初始化对象

c# - 如何在远程服务器上使用 BitmapImage 设置 UriSource?

.net - 通过 ElementName 将 UserControl 属性绑定(bind)到其子级会导致绑定(bind)错误

c# - C# 中的全局变量替代品?

c# - 编辑一列中的所有行,数据表c#

c# - 如何精确测量字符的宽度?

c# - MVVM C#​​ 如何将异步数据加载到属性中?

c# - MVVM:在跟踪 IsSynchronizedWithCurrentItem 时绑定(bind)到列表 IsSelected

c# - WPF 快速转换器 : Hide element on empty list

c# - WPF 将 bool 值转换为彩色字符串