C# 从XAML创建的GUI获取以前的文本值

C# 从XAML创建的GUI获取以前的文本值,c#,binding,textbox,textchanged,C#,Binding,Textbox,Textchanged,在更改XAML创建的文本框之前,是否有方法获取该文本框中的上一个文本值 我的目标是让用户在文本框中输入值,检查它是数字还是以“.”开头。否则,将文本框值返回到上一个数字 XAML代码: <Label x:Name="Label_F" Content="F" Margin="5" VerticalAlignment="Center" Width="20"/> <TextBox x:Name="Box_F" Text="{Binding F, Mode=TwoWay, Update

在更改XAML创建的文本框之前,是否有方法获取该文本框中的上一个文本值

我的目标是让用户在文本框中输入值,检查它是数字还是以“.”开头。否则,将文本框值返回到上一个数字

XAML代码:

<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"/>

不要先设置值,然后再恢复,而是查看新值是否是可以设置为
F
的有效值

如果是,设置它。如果没有,则不要执行任何操作,这意味着旧值将保留在
文本框中

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.
    }
}
编辑
对第二次验证做了一个小的更改。

不是先设置值然后再恢复,而是查看新值是否是可以设置为
F
的有效值

如果是,设置它。如果没有,则不要执行任何操作,这意味着旧值将保留在
文本框中

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.
    }
}
编辑 对第二次验证做了一个小改动