我试图这样做当用户输入零以下的数字或字符串时,文本框背景变为红色。如果输入的数字大于或等于0,则文本框保持相同的白色。在用户输入正确的整数之前,它将为红色。我还希望将数字存储在变量中。我编写了下面的代码,但它是我在cmd程序中使用的代码的混合,因此不确定它是如何在WPF中完成的。
_heightVal = 0;
private void TxtFeetInput_TextChanged(object sender, TextChangedEventArgs e)
{
_heightVal = double.Parse(txtFeetInput.Text);
if (heightVal = "")/*any string*/
{
textBox1.Background = Brushes.Red;
}
else if (_heightVal < 0)
{
textBox1.Background = Brushes.Red;
}
else
{
textBox1.Background = Brushes.White;
}
}
请尝试以下方法:
double i = 0;
string s = txtFeetInput.Text;
bool result = double.TryParse(s, out i);
if(result && i >= 0){
textBox1.Background = Brushes.White;
}else{
textBox1.Background = Brushes.Red;
}
您可以使用以下内容。
private void TxtFeetInput_TextChanged(object sender, TextChangedEventArgs e)
{
if (string.IsNullOrEmpty(txtFeetInput.Text))
{
textBox1.Background = Brushes.White;
return;
}
textBox1.Background = double.TryParse(txtFeetInput.Text, out var value)
&& value >= 0?
Brushes.White : Brushes.Red;
}