【问题标题】:Value not Set when binding Nullable Values绑定 Nullable 值时未设置值
【发布时间】:2014-01-25 02:18:24
【问题描述】:

嗨,芽,

我有一个 Nullable int 属性,它绑定到实现 INotifyPropertyChanged 的​​ TextBox,在运行时当我更改 TextBox 的值并失去焦点时。财产的二传手没有击中。 :-(

有什么想法吗??!

顺便说一句,是的 BindingMode 设置为 TwoWay

【问题讨论】:

    标签: c# windows-runtime winrt-xaml


    【解决方案1】:

    我不确定这是否适用于 WinRT,但在 WPF 中,您需要在绑定中指定 TargetNullValue

    <TextBox Text="{Binding myNullableInt, TargetNullValue={x:Static sys:String.Empty}}"/>
    

    这样,当用户删除文本时,它绑定的属性将更新为null。检查此SO question 以供参考。

    更新:

    很遗憾,WinRT 绑定中没有TargetNullValue。因此,您可用的选项是使用@TylerD87 的方法还是创建并使用转换器将空字符串转换为空值,如here 所述。

    【讨论】:

      【解决方案2】:

      我可能会考虑将 TextBox 绑定到字符串属性而不是可为空的 int,因为那里可能存在某种绑定错误。然后你总是可以做这样的事情:

      int outValue;
      int? nullableOutValue;
      nullableOutValue = int.TryParse(stringValue, out outValue) ? (int?)outValue : null;
      

      然后将您的字符串属性转换为正确的值。您可以在属性的 setter 中执行此操作,并在需要输入 int 时为非法值提供错误检查。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-26
        • 2021-08-08
        • 1970-01-01
        • 2014-12-30
        • 2011-01-05
        • 1970-01-01
        • 1970-01-01
        • 2012-06-22
        相关资源
        最近更新 更多