您可以使用此值轉換器,但你並不需要。您可以簡單地使用綁定標記擴展的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