【问题标题】:Getting Previous Text Value from XAML Created GUI从 XAML 创建的 GUI 获取先前的文本值
【发布时间】:2018-11-25 18:17:35
【问题描述】:

有没有办法在 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# binding textbox textchanged


    【解决方案1】:

    不要先设置值,然后再还原,而是查看新值是否是可以设置为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.
        }
    }
    

    编辑

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

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 2014-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      相关资源
      最近更新 更多