代码之家  ›  专栏  ›  技术社区  ›  VoodooChild

如何将数据绑定的零双精度值转换为空字符串?

  •  3
  • VoodooChild  · 技术社区  · 14 年前

    我有这个付款对象

    public class Payment 
    {
        public Guid Id { get; set; }
        public double Amount { get; set; }
    }
    

    <TextBox x:Name="_AmountTB" Text="{Binding Path=Amount, Mode=TwoWay}" />
    

    我要求每当金额为0时,我不在文本框中显示任何内容,如何做到这一点?

    我在想某种转换器,但我需要有人告诉我怎么做请?!

    谢谢,

    2 回复  |  直到 14 年前
        1
  •  4
  •   Josh    14 年前

    你可以使用一个值转换器,但你不需要。您可以简单地使用绑定标记扩展的StringFormat来指定 three-part custom numeric format string . 它看起来是这样的:

    <TextBox Text="{Binding Path=Amount, StringFormat='0.00;-0.00;#'}" />
    

    字符串格式的分号告诉.NET使用第一节设置正数格式,中间节设置负数格式,最后一节设置零值格式。棘手的部分是为零部分得到一个空字符串,我使用了一个磅(#)符号。此格式说明符在其位置显示有效数字,但由于使用该节时该值始终为零,因此会导致空字符串。

    public class ZeroConverter : IValueConverter {
    
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return String.Format(culture, "{0:0.00;-0.00;#}", value);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string str = value as string;
            if (!String.IsNullOrEmpty(str)) {
                return System.Convert.ChangeType(str, targetType, culture);
            }
            return System.Convert.ChangeType(0, targetType, culture);
        }
    
    }
    

    XAML公司

    <UserControl>
        <UserControl.Resources>
            <local:ZeroConverter x:Key="ZeroToEmpty" />
        </UserControl.Resources>
    </UserControl>
    <TextBox Text="{Binding Path=Amount, Converter={StaticResource ZeroToEmpty}}" />
    
        2
  •  1
  •   VoodooChild    14 年前
    public class BlankZeroConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter,
                                  System.Globalization.CultureInfo culture)
            {
                if (value == null)
                    return null;
    
                if (value is double)
                {
                    if ((double)value == 0)
                    {
                        return string.Empty;
                    }
                    else
                        return value.ToString();
    
                }
                return string.Empty;
            }
       }