有没有一种方法可以在XAML创建的文本框中获取之前的文本值,然后再进行更改?
我的目标是让用户在文本框中输入输入值,检查输入值是否为数字或以".“开头。如果不是,则将textbox值返回到前一个数字。
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");
发布于 2018-06-16 07:14:36
查看新值是否为可以设置为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.
}
}
编辑
对第二个验证做了一个小改动。
https://stackoverflow.com/questions/50883421
复制相似问题