2011-02-11 111 views
7

結合我有這個文本框:格式化雙向百分比WPF

<TextBox Text="{Binding Path=TaxFactor, StringFormat=P}" /> 

它正確地顯示0.055%,但它不工作回去。當我輸入百分比時,由於百分比符號而失敗。如果我嘗試只寫一個數字,例如5,我會得到500%。我必須寫0.05才能工作。

我是否必須編寫一個自定義轉換器才能返回我的百分比?如果是這樣,我該如何解決區域特定的百分比格式?

回答

10

您需要編寫一個自定義轉換器。注意:這一個假設值被存儲在範圍爲0〜100,而不是0到1

public object Convert(object value, Type targetType, object parameter, 
         System.Globalization.CultureInfo culture) 
{ 
    if (string.IsNullOrEmpty(value.ToString())) return 0; 

    if (value.GetType() == typeof(double)) return (double)value/100; 

    if (value.GetType() == typeof(decimal)) return (decimal)value/100;  

    return value; 
} 

public object ConvertBack(object value, Type targetType, object parameter, 
          System.Globalization.CultureInfo culture) 
{ 
    if (string.IsNullOrEmpty(value.ToString())) return 0; 

    var trimmedValue = value.ToString().TrimEnd(new char[] { '%' }); 

    if (targetType == typeof(double)) 
    { 
     double result; 
     if (double.TryParse(trimmedValue, out result)) 
      return result; 
     else 
      return value; 
    } 

    if (targetType == typeof(decimal)) 
    { 
     decimal result; 
     if (decimal.TryParse(trimmedValue, out result)) 
      return result; 
     else 
      return value; 
    } 
    return value; 
} 

的調用它是這樣的:

<TextBox Text="{Binding Path=TaxFactor, Mode=TwoWay, StringFormat=P, 
     Converter={StaticResource percentStringFormatConverter} /> 

這是從一些Silverlight的代碼,但應與WPF

+1

足夠滿足我當前的需求,雖然轉換器需要一些調整(它不會將數字除以100)並忽略本地化。謝謝。 – 2011-02-11 11:56:52

6

添加到ChrisF的答覆工作,我結束了使用(僅適用於小數)轉換器:

class DecimalPercentageConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, 
        System.Globalization.CultureInfo culture) 
    { 
     return value; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, 
           System.Globalization.CultureInfo culture) 
    { 
     if (targetType != typeof(decimal) || value == null) 
      return value; 

     string str = value.ToString(); 

     if (String.IsNullOrWhiteSpace(str)) 
      return 0M; 

     str = str.TrimEnd(culture.NumberFormat.PercentSymbol.ToCharArray()); 

     decimal result = 0M; 
     if (decimal.TryParse(str, out result)) { 
      result /= 100; 
     } 

     return result; 
    } 
}