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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18964518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:42:37  来源:igfitidea点击:

wpf converters with different decimal number

wpfxamlconverter

提问by Unplug

I have a lot of numbers to deal with from my UI. I want some of them to be no decimal places, some to be 2 decimals, and others to be however they are entered (3 or 4 decimal places).

我的用户界面中有很多数字要处理。我希望其中一些没有小数位,一些是 2 位小数,而另一些则是输入的(3 或 4 位小数)。

I have a converter named DoubleToStringConverter like this:

我有一个名为 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;
    }
}

Is there a way to write just one converter to achieve this? It seems there is no way to have a parameterized converter. The StringFormat in xaml seems to conver string to other type of data. It does not allow to display a substring from xaml.

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

I can only think of making IntegerToStringConverter, Double2ToStringConverter, Double3ToStringConverter, etc. But I'd like to see whether there is a more efficient way.

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

回答by Reed Copsey

You can pass the number of decimal points to use as the parameter, which can then be specified in XAML via ConverterParameterwithin the binding.

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

That being said, for formatting numbers, you don't actually need a converter at all. Bindings support StringFormatdirectly, which can be used to do the formatting entirely in XAML:

话虽如此,对于格式化数字,您实际上根本不需要转换器。StringFormat直接绑定支持,可用于完全在 XAML 中进行格式化:

<TextBox Text="{Binding Path=TheDoubleValue, StringFormat=0:N2} />