双向比例在WPF格式化绑定 [英] Two way percentage formatted binding in WPF
问题描述
我有这样的文本框:
<TextBox Text="{Binding Path=TaxFactor, StringFormat=P}" />
它正确地显示 0.05
为 5%
,但它不工作,回去。当我输入一个百分比,它失败,因为百分比符号。如果我试着写只是一个数字,如 5
,我得到 500%
代替。我要写 0.05
为它工作。
It correctly displays 0.05
as 5%
, but it doesn't work going back. When I type in a percentage, it fails because of the percent symbol. If I try writing just a number, like 5
, I get 500%
instead. I have to write 0.05
for it to work.
我必须写一个自定义转换,让我的百分比回来?如果是这样,我怎么周围设置特定百分比的格式得到什么呢?
Do I have to write a custom converter to get my percentage back? And if so, how do I get around locale-specific percentage formats?
推荐答案
您需要编写一个自定义的转换器。注意:这一个假设值存储在范围为0〜100,而不是0到1
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} />
这是一些Silverlight的code,但应与WPF 的
这篇关于双向比例在WPF格式化绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!