简体   繁体   中英

How can I remove a character from a C#.net WPF textbox before it's shown?

I have a project in C#.net using a WPF textbox that validates a character like * as the first character entered. If this character is entered, the rest of the text is good but I cannot show nor use the character. How can I remove the character from the string early enough to not show it? I've attempted using the KeyDown event but while the event is active, there is no data to remove. And if I use the KeyUp event the data is shown for a second. I've previously used a KeyPress event in VB6 to achieve this which worked because the value was simultaneously in the code but not in the textbox. As far as I can tell a WPF textbox does not have this event. What can I do?

Code:

private void UserInput_KeyUp(object sender, KeyEventArgs e)
{
     //get ascii value from keyboard input
     int Ascii = (int)e.Key;
     //get char value to know what to remove as a string
     char CharAscii = (char)Ascii;

     If(Ascii == InputPrefix)
     {
            PrefixValidated = true;
            UserInput.Text = UserInput.Text.Replace(CharAscii.ToString(), string.Empty);
     }
}

The same code is in the KeyDown event and I've tried it using one or the other and both.

it may be a bit of a rough solution but you could use a PreviewTextInupt event I belive.

    private bool PrefixValidated = false;
    private string CheckUserInput;

    private void TextBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        CheckUserInput = CheckUserInput + e.Text;

        if (CheckUserInput.ElementAt(0).ToString() == "*" && e.Text != "*")
        {
            e.Handled = false;
        }

        else if (CheckUserInput.ElementAt(0).ToString() == "*")
        {
            PrefixValidated = true;
            e.Handled = true;
        }

        else
        {
            e.Handled = true;
        }
    }

Thanks to Dark Templar for helping with the discovery of this solution. Using PreviewTextInput and validating the character only if there are no other characters in the textbox seems to give the correct result.

Setting e.Handled = true stops the character from actually entering the textbox even for a second so the user is never aware of the prefix.

Code:

private void UserInput_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        //if this is the first character entered, the textbox is not yet populated
        //only perform validation if the character is a prefix
        if (UserInput.Text != "")
            return; 

        char CharAscii = (char)ScannerPrefix;

        if (e.Text == CharAscii.ToString())
        {
            PrefixValidated = true;
            e.Handled = true;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM