【问题标题】:The textbox should never be empty. c#文本框永远不应为空。 C#
【发布时间】:2020-10-30 11:46:44
【问题描述】:

我不希望我的文本框为空。我希望它在它为空之前保留该值,并在它被删除时写入它。我正在使用 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;
            }
        }
    }

【问题讨论】:

  • 请尝试e.KeyCode == Keys.Delete,如here 所述。还请仔细检查,如果此方法实际上是 KeyDown 并且未附加到 KeyPress。这在您的文本框选项中设置。
  • 按 Backspace 时会怎样?使用 TextChanged 事件并将文本保存在变量中不是更好吗?
  • 如果我使用TextChanged,如何保留以前的数据。只要按下删除按钮,我就可以检索到 Textbox 中写入的数据。
  • 我使用 wpf。在 Wpf 中找不到按键事件。

标签: c# wpf null textbox


【解决方案1】:

您可以处理 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 是否为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-22
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2015-09-09
    相关资源
    最近更新 更多