简体   繁体   中英

WPF TextBox's value updates while I am typing

I have bound two TextBoxes in TwoWay Mode to a double? value via DoubleConvertor .
And values update while I am typing.
1st case. If I type a double value in the first TB, switch to the second, and press an invalid symbol, the value is erased by the update. 2nd case. If I enter too many digits, the tail digits are corrected to zero.

public class DoubleConvertor : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is not double doubleValue)
        {
            return DependencyProperty.UnsetValue;
        }

        return doubleValue.ToString("0.########", CultureInfo.InvariantCulture);
    }

    public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is not string stringValue)
        {
            return null;
        }
        
        var parsed = double.TryParse(stringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out var doubleValue);
        return parsed ? doubleValue : null;
    }
}

The way how I bind to the double? value:

<TextBox>
    <TextBox.Text>
        <Binding Converter="{StaticResource DoubleConvertor}"
                 Path="Value" Mode="TwoWay"
                 UpdateSourceTrigger="PropertyChanged"/>
    </TextBox.Text>
</TextBox>

How to make it not update the text field while typing?
There is the source code: GitHub .

The UpdateSourceTrigger=PropertyChanged defines that the binding is updated on every change of the property (eg on every char that is input).

If you want the update to only happen when the teyt box loses focus (ie another elemtent is focused), you need to set UpdateSourceTrigger=LostFocus .

Your text box could then look like this:

<TextBox>
    <TextBox.Text>
        <Binding Converter="{StaticResource DoubleConvertor}"
                 Path="Value" Mode="TwoWay"
                 UpdateSourceTrigger="LostFocus"/>
    </TextBox.Text>
</TextBox>     

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