【问题标题】:how to convert a databound zero double value to an empty string?如何将数据绑定的零双精度值转换为空字符串?
【发布时间】:2010-07-20 02:26:41
【问题描述】:

我有这个支付对象

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

这是绑定到文本框的数据

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

我要求,只要 Amount 为 0,那么我在 TextBox 中不显示任何内容,如何做到这一点?

我正在考虑某种转换器,但我需要有人告诉我如何做到这一点吗?!

谢谢,

巫毒

【问题讨论】:

    标签: c# silverlight data-binding


    【解决方案1】:

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

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

    字符串格式中的分号告诉 .NET 使用第一部分格式化正数,中间部分格式化负数,最后一部分格式化零值。棘手的部分是为我使用井号 (#) 符号的零部分获取一个空字符串。此格式说明符在其位置显示一个有效数字,但由于在使用该部分时该值将始终为零,因此会产生一个空字符串。

    请注意,StringFormat 需要 Silverlight 4。如果您使用的是 Silverlight 3,则需要一个值转换器。 (您可能希望更稳健地处理错误...)

    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】:
    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;
            }
       }
    

    【讨论】:

      猜你喜欢
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      相关资源
      最近更新 更多