如果 TextBox 有 8 个字符,则清除 xaml C#

The TextBox is cleared if it has 8 characters xaml C#

我想在 textBox 组件有 4 个元素(8 个字符,带空格)后使它更清晰

Text box

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

未测试 - 可能需要根据 space 适合 8 个字符的方式进行调整。如果是 4 个字符,中间有 spaces 那只有 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;
    }
}