首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从XAML创建的GUI获取上一个文本值

从XAML创建的GUI获取上一个文本值
EN

Stack Overflow用户
提问于 2018-06-16 06:34:08
回答 1查看 25关注 0票数 0

有没有一种方法可以在XAML创建的文本框中获取之前的文本值,然后再进行更改?

我的目标是让用户在文本框中输入输入值,检查输入值是否为数字或以".“开头。如果不是,则将textbox值返回到前一个数字。

XAML代码:

代码语言:javascript
复制
<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"/>

代码

代码语言:javascript
复制
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");
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-16 07:14:36

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

如果是,则设置它。如果不是,什么也不要做,这意味着旧值将保留在TextBox中。

代码语言:javascript
复制
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.
    }
}

编辑

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50883421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档