2010-07-20 40 views
3

我有这样的付款对象如何将数据绑定零倍值转换为空字符串?

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

这是数据绑定到一个文本框

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

我需要每当量为0,那我就不在文本框中显示任何东西,怎么能这样做?

我在想某种转换器,但我需要有人向我展示如何做到这一点?

感谢,

巫毒

回答

4

您可以使用此值转换器,但你并不需要。您可以简单地使用绑定标记扩展的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}}" /> 
+0

我很高兴,直到我阅读了有关SL4 :( – VoodooChild 2010-07-20 02:42:55

+0

最后一行我终于来到在我的懒惰,结束了(见我的回答) – VoodooChild 2010-07-20 03:51:33

+1

啊,我只是把它添加到我的答案。 – Josh 2010-07-20 03:57:19

1
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; 
     } 
    } 
相关问题