Overriding the default key behavior in a TextBox

I just implemented a quick autocomplete function in TextBox, which pulls a line from a rather small list and "completes" this word. The template TextBoxremains in the place where it was, starting from the last keystroke, and the part of the word that the user has not yet typed becomes highlighted, so that the start of entering anything else will delete this entry section.

The sticker is that I need to have it in such a way that after completion and partial highlighting, the space works like the “accept” key - for example, it moves the carriage to the end of the completed word. However, no matter what I seem to do with the hit, it deletes the selected part of the word (replacing it with a space character, just as if you hit any other key).

I tried this:

private void textBoxIncidentLogTypes_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Space)
    {
        textBoxIncidentLogTypes.CaretIndex = textBoxIncidentLogTypes.Text.Length;
    }
}

But while this “works,” it starts after the white space key destroys the best part of the phrase. Is there a way to capture a keystroke before it is typed in TextBox?

+3
source share
2 answers

PreviewKeyDown ; , TextBox .

, , TextBox (.. ), e.Handled PreviewKeyDown true ( ) false ( TextBox ).

+2

PreviewKeyDown KeyDown KeyEventArgs e.Handled true!

private void textBoxIncidentLogTypes_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Space)
    {
        textBoxIncidentLogTypes.CaretIndex = textBoxIncidentLogTypes.Text.Length;
        e.Handled = true;
    }
}
+1

Source: https://habr.com/ru/post/1729386/


All Articles