4

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).

I have a converter named DoubleToStringConverter like this:

[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.

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

2
  • Why don't you use the parameter to specify your significant digits? Commented Sep 23, 2013 at 16:44
  • Yes. You can add a parameter to your binding. It's available in the method signature--parameter. You can convert that to a string, then determine the cast you need to make (int/double/long), then call ToString on it. use targetType on the backside to determine what to parse. Not sure where you're having an issue here. Commented Sep 23, 2013 at 16:47

1 Answer 1

8

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

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

<TextBox Text="{Binding Path=TheDoubleValue, StringFormat=0:N2} /> 
Sign up to request clarification or add additional context in comments.

6 Comments

:/ StringFormat="0:N2" and "{" + parameter + "}" would be easier.
@Will What do you mean about "{" + parameter + "}" being easier? Good point about the "0:N2".
Oh, er, constructing the format string in the method body. Which isn't really necessary here. Carry on.
I have this <TextBlock.Text><Binding Path="TheDoubleValue" Converter="{StaticResource doubleToStringConverter}" Mode="OneWay" StringFormat="{}{0:N2} Kg"></Binding></TextBlock.Text> But the output is like: 50 Kg instead of 50.00 Kg
@Martin Remove the converter - it's turning your number into a string.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.