简体   繁体   中英

String To Double Converter with IValueConverter C#

I have a View in which I should be able to input doubles. The thing is, I can only input whole numbers such as "100" but not "100.4". All my background calculations run on doubles though. I'm now trying to bypass the problem by implementing a StringToDoubleConverter but my C# knowledge is still very limited.

I've implemented this into my UserControl.Resources tag

<local:StringToDoubleConverter x:Key="StringToDouble"/>

and created a new class StringToDoubleConverter:

class StringToDoubleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string stringNumber = value as string;
            double.TryParse(stringNumber, out double val);
            return val;
        }
    }

Finally I've implemented the converter into my binding:

<TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DelayModel.DelayTime, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource StringToDouble}}"/>

My DelayTime in my DelayModel looks like this:

private double _delayTime;

public double DelayTime
{
    get
    {
        return _delayTime;
    }
    set
    {
        if (value != _delayTime)
        {
            _delayTime = value; NotifyPropertyChanged();
        }
    }
}

I know my converter is somehow wrong. I'm struggling to get the right code to convert the string I want to input in my View to doubles.

For example: I want to input "0.7" into my View and DelayTime should actually get "0.7" and not just the "7". Is TryParse oder double.Parse(value) correct?

You don't need StringToDoubleConverter.

The problem is using UpdateSourceTrigger=PropertyChanged. It update the source after pressing each key. If you put the point character, it update the source with string value "0." what give you back "0" without point. You can change UpdateSourceTrigger to Default and update Source manually when you press Enter with KeyDown event

<TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DelayModel.DelayTime}" KeyDown="TextBox_KeyDown"/>

and code behind

private void TextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if(e.Key == Key.Enter)
            (sender as TextBox).GetBindingExpression(TextBox.TextProperty).UpdateSource();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM