Search code examples
c#bindingtextbox

C# WPF add character to textbox without binding


Can i simply add characters without binding this characters to my ViewModel? I need these to show physical units like cm, mm, m, cm^3, ...

XAML:

<TextBox 
Text="{Binding value_top}" //sth. like + "cm"
HorizontalAlignment="Left" 
VerticalAlignment="Top" 
Width="50"/>

VW:

value_top = 22.9

Output aim:

22.9 cm

I know, I can overlay a Label, but i would like to know if there is another possibility.


Solution

  • Create a converter which will take the double and return a string. Here is an untested example to get you started:

    public class DoubleToString: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var dbl = (double) value;
    
            return $"{dbl} cm";           
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Double.Parse(Regex.Match(value.ToString(), "[\d.]+").Value);    
        }
    }