具有不同十进制数的wpf转换器

Unp*_*lug 3 wpf xaml converter

我的UI中有很多数字要处理.我希望它们中的一些不是小数位,有些是小数点后2位,而其他的则是输入(小数点后3或4位).

我有一个名为DoubleToStringConverter的转换器,如下所示:

[ValueConversion(typeof(double), typeof(string))]
public class DoubleToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value == null ? null : ((double)value).ToString("#,0.##########");
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double retValue;
        if (double.TryParse(value as string, out retValue))
        {
            return retValue;
        }
        return DependencyProperty.UnsetValue;
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法只编写一个转换器来实现这一目标?似乎没有办法让参数化转换器.xaml中的StringFormat似乎将字符串转换为其他类型的数据.它不允许显示来自xaml的子字符串.

我只能想到制作IntegerToStringConverter,Double2ToStringConverter,Double3ToStringConverter等等.但我想看看是否有更有效的方法.

Ree*_*sey 5

您可以传递要用作的小数点数,parameter然后可以通过ConverterParameter绑定在XAML中指定.

话虽这么说,为了格式化数字,你实际上根本不需要转换器.绑定支持StringFormat直接,可用于完全在XAML中进行格式化:

<TextBox Text="{Binding Path=TheDoubleValue, StringFormat=0:N2} />
Run Code Online (Sandbox Code Playgroud)