首页 > 解决方案 > 从 XAML 创建的 GUI 获取先前的文本值

问题描述

有没有办法在更改之前在 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"/>

代码

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");

标签: c#bindingtextboxtextchanged

解决方案


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

如果是,请设置它。如果没有,不要做任何事情,这意味着旧值将保留在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.
    }
}

编辑

对第二次验证做了一个小改动。


推荐阅读