Search code examples
c#wpftextboxwpf-controls

Need help developing and Binding a Double <--> Converter


I develop engineering applications and therefore constantly deal with double numbers. Being a newbie and since ComboBoxes and other controls prefer strings, my models are string-based:

Diameter = "0.523";

I have done Google searches and have some preliminary (confusing, contradictory) info about Converters: could use a unified explanation.

The IValueConverter interface establishes a Convert() and a ConvertBack() pair, but which is the direction of each? The Converter is XAML bound to, say, a TextBox and my model deals with double. Does the Convert() half act going out of the TextBox or into it?

My objective is to add a warning near the red rectangle that is formed when illegitimate numbers are typed: "The floating point number that you typed has an incorrect format".

I wrote 2 Convertor classes: DoubleToString and StringToDouble. Not sure which is the proper one (plus, both are crashing).


Solution

  • Most of the time people only use the Convert method for their work. ConvertBack is used in when convertion is need for both side. XAML to Model vice versa

    Here is a sample for double. You can further format the value as per your need.

    [ValueConversion(typeof(double) ,typeof(string))]
    public class DoubleConverter : IValueConverter
    {
        public object Convert(object value ,Type targetType ,object parameter ,CultureInfo culture)
        {
            double doubleType = (double)value;
            return doubleType.ToString();
        }
    
        public object ConvertBack(object value ,Type targetType ,object parameter ,CultureInfo culture)
        {
            string strValue = value as string;
            double resultDouble;
            if ( double.TryParse(strValue ,out resultDouble) )
            {
                return resultDouble;
            }
            return DependencyProperty.UnsetValue;
        }
    }