首页 > 解决方案 > 如果 TextBox 有 8 个字符 xaml C#,则将其清除

问题描述

我想让 textBox 组件在它有 4 个元素(带空格的 8 个字符)之后变得清晰

文本框

标签: c#xamltextbox

解决方案


处理文本框的KeyDown事件并检查textBox.Text.Length == 8. 您还可以强制每个其他字符为空格。

未经测试- 可能需要根据空格适合 8 个字符的方式进行调整。如果是 4 个字符,它们之间有空格,则只有 7 个字符。

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (textBox1.Text.Length == 8)
    {
        // do something with the text

        textBox1.Text = "";     // clear the textbox
    }
    // optional else if to only allow spaces for every other character
    else if (textBox1.Text.Length % 2 == 1  // odd index characters
        && e.KeyCode != Keys.Space)         // must be spaces
    {
        e.Handled = true;
    }
}

推荐阅读