Search code examples
c#bindingtextboxtextchanged

Getting Previous Text Value from XAML Created GUI


Is there a way to get the previous text value in a XAML created textbox before it is changed?

My goal is for user to enter input value into a textbox,check if it is a number or begins with ".". If not, return textbox value back to previous number.

XAML Code:

<Label x:Name="Label_F" Content="F" Margin="5" VerticalAlignment="Center" Width="20"/>
<TextBox x:Name="Box_F" Text="{Binding F, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding IntegralCageCheck, Converter={StaticResource booleaninverter}}" Margin="5" Width="50" VerticalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>

Code

public string F
{
    get { return _F; }
    set
    {
        _F = value;
        double temp;

        bool result = double.TryParse(value, out temp);

        if (!char.IsDigit(Convert.ToChar(_F)) && _F != ".")
            {
            _F = _F.previousvalue; // Using as example
            }
        else { FrontPanelVariables.F = temp * 25.4; }

        RaisePropertyChanged("F");

Solution

  • Instead of setting value at first and then reverting, see if the new value is a valid value that you can set to F.

    If yes, set it. If not, don't do anything, which means the old value will remain in the TextBox.

    private string _F;
    public string F
    {
        get { return _F; }
        set
        {
            // See if the new value is a valid double.
            if (double.TryParse(value, out double dVal))
            {
                // If it is, set it and raise property changed.
                _F = value;
                RaisePropertyChanged("F");
            }
            else
            {
                // If not a valid double, see if it starts with a "."
                if (value.StartsWith("."))
                {
                    // If it does, then see if the rest of it is a valid double value.
                    // Here this is a minimal validation, to ensure there are no errors, you'll need to do more validations.
                    var num = "0" + value;
                    if (double.TryParse(num, out dVal))
                    {
                        _F = value;
                        RaisePropertyChanged("F");
                    }
                }
            }
    
            // Use dVal here as needed.
        }
    }
    

    EDIT

    Made a small change to the second validation.