[英]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
是否為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.