在WPF绑定中将值设置为null

Shi*_*mmy 114 string wpf binding nullable .net-3.5

请看下面一行

<TextBox Text="{Binding Price}"/>
Run Code Online (Sandbox Code Playgroud)

上面的价格属性是Decimal?(可以为十进制).

我希望如果用户删除文本框的内容(即输入空字符串,它应该自动更新源为null(在VB中为Nothing).

关于如何做到'Xamly'的任何想法?

Shi*_*mmy 222

我使用的是.NET 3.5 SP1,因此非常简单:

<TextBox Text="{Binding Price, TargetNullValue=''}"/>
Run Code Online (Sandbox Code Playgroud)

哪个代表(感谢Gregor的评论):

<TextBox Text="{Binding Price, TargetNullValue={x:Static sys:String.Empty}}"/>
Run Code Online (Sandbox Code Playgroud)

sysSystemin 的导入的xml命名空间mscorlib:

xmlns:sys="clr-namespace:System;assembly=mscorlib"
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.

  • 实际上TargetNullValue工作得很好.它的作用是设置给定值和null之间的等价.因此,在这种情况下,当绑定值为null时,它将显示一个空字符串,当目标的值为空字符串时,它将绑定值设置为null. (13认同)
  • TargetNullValue有效.使用值转换器时,我得到了相同的结果.您还可以简化表达式:<TextBox Text ="{Binding Price,TargetNullValue =''}"/> (4认同)
  • 我很困惑 - OP说:"..应该自动更新源为null [当Target是一个空字符串].",但TargetNullValue更新_Target_,而不是_Source_! (2认同)

Tho*_*que 11

这个值转换器应该做的伎俩:

public class StringToNullableDecimalConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
        CultureInfo culture)
    {
        decimal? d = (decimal?)value;
        if (d.HasValue)
            return d.Value.ToString(culture);
        else
            return String.Empty;
    }

    public object ConvertBack(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        string s = (string)value;
        if (String.IsNullOrEmpty(s))
            return null;
        else
            return (decimal?)decimal.Parse(s, culture);
    }
}
Run Code Online (Sandbox Code Playgroud)

在ressources中声明此转换器的实例:

<Window.Resources>
    <local:StringToNullableDecimalConverter x:Key="nullDecimalConv"/>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

并在绑定中使用它:

<TextBox Text="{Binding Price, Converter={StaticResource nullDecimalConv}}"/>
Run Code Online (Sandbox Code Playgroud)

注意TargetNullValue这里不合适:它用于定义当source绑定为null 时应使用哪个值.这里Price不是来源,它是来源的属性......

  • 转换器是执行此操作的正确方法,您无法在XAML中定义这些转换器.转换器允许您在数据绑定中更改默认的"对象"转换行为,这是您想要做的. (2认同)

Tim*_*hyP 5

您可以尝试使用ValueConverter(IValueConverter) http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx

在我的脑后,有点像:

public class DoubleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        return (double)value;
    }

    public object ConvertBack(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
    var doubleValue = Convert.ToDouble(value);

    return (doubleValue == 0 ? null : doubleValue);
    }
}
Run Code Online (Sandbox Code Playgroud)

(可能需要一些调整)