2010-07-20 23 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; 
     } 
    } 
相關問題