您可以使用此值转换器,但你并不需要。您可以简单地使用绑定标记扩展的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}}" />
我很高兴,直到我阅读了有关SL4 :( – VoodooChild 2010-07-20 02:42:55
最后一行我终于来到在我的懒惰,结束了(见我的回答) – VoodooChild 2010-07-20 03:51:33
啊,我只是把它添加到我的答案。 – Josh 2010-07-20 03:57:19