文本框永远不应为空。 C#
The textbox should never be empty. c#
我不希望我的文本框为空。我希望它在它为空之前保留值并在它被删除时写入它。我正在使用 KeyDown 事件,但它不起作用。按下 Delete 键时不触发。哪个事件适合正确触发。
我的代码
private static void textBox_KeyDown(object sender,KeyEventArgs e)
{
var textBox = sender as TextBox;
var maskExpression = GetMaskExpression(textBox);
var oldValue = textBox.Text;
if (e.Key == Key.Delete)
{
if (textBox.Text == string.Empty || textBox.Text == "")
{
MessageBox.Show("Not null");
textBox.Text = oldValue;
}
}
}
您可以处理 TextChanged
并将先前的值存储在字段中:
private string oldValue = string.Empty;
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (string.IsNullOrEmpty(textBox.Text))
{
MessageBox.Show("Not null");
textBox.Text = oldValue;
}
else
{
oldValue = textBox.Text;
}
}
请注意,oldValue
将在每次按键时重置。另请注意 string.Empty
等于 ""
因此您不需要两个条件来检查 string
是否为空。
我不希望我的文本框为空。我希望它在它为空之前保留值并在它被删除时写入它。我正在使用 KeyDown 事件,但它不起作用。按下 Delete 键时不触发。哪个事件适合正确触发。
我的代码
private static void textBox_KeyDown(object sender,KeyEventArgs e)
{
var textBox = sender as TextBox;
var maskExpression = GetMaskExpression(textBox);
var oldValue = textBox.Text;
if (e.Key == Key.Delete)
{
if (textBox.Text == string.Empty || textBox.Text == "")
{
MessageBox.Show("Not null");
textBox.Text = oldValue;
}
}
}
您可以处理 TextChanged
并将先前的值存储在字段中:
private string oldValue = string.Empty;
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (string.IsNullOrEmpty(textBox.Text))
{
MessageBox.Show("Not null");
textBox.Text = oldValue;
}
else
{
oldValue = textBox.Text;
}
}
请注意,oldValue
将在每次按键时重置。另请注意 string.Empty
等于 ""
因此您不需要两个条件来检查 string
是否为空。