我有这个文本框:
<TextBox Text="{Binding Path=TaxFactor, StringFormat=P}" />
它正确显示0.05
as 5%
,但是回去是不行的。当我输入百分比时,由于百分比符号而导致失败。如果我尝试只写一个数字,比如5
, I get 500%
反而。我必须写0.05
让它发挥作用。
我是否必须编写一个自定义转换器才能恢复我的百分比?如果是这样,我如何解决特定于区域设置的百分比格式?
您需要编写一个自定义转换器。注意:这里假设值存储在 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)