I have this textbox:
It correctly displays 0.05
as 5
Adding to ChrisF's answer, the converter I ended up using (only for decimals):
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;
}
}
You need to write a custom converter. NOTE: this one assumes that the values are stored in the range 0 to 100 rather than 0 to 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;
}
The call it like this:
<TextBox Text="{Binding Path=TaxFactor, Mode=TwoWay, StringFormat=P,
Converter={StaticResource percentStringFormatConverter} />
this is from some Silverlight code, but should work with WPF