开发者

Overriding default key behaviour in a TextBox

I've just implemented a quick autocomplete feature in a TextBox that pulls a string out of a fairly small list and "completes" the word. The TextBox caret stays at the location it was in from the last keypress, and the part of the word that the user has yet to type becomes highlighted, such that beginning to type something else will remove this section of the input.

The stickler is that I need to have it such that, upon completion and part-highlighting, the space bar works as an "accept" key - for instance it'd move the caret to the end of the completed word. However no matter what I seem to do hitting space 开发者_运维百科deletes the highlighted part of the word (replacing it with a space character, just as if you'd hit any other key).

I've 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 gets fired after the space key has demolished the best part of a phrase. Is there any way to capture the keypress before it gets typed into the TextBox?


Try handling the PreviewKeyDown event instead; it should occur before the TextBox has had a chance to process the key.

Depending on whether you want the TextBox to also handle the space key or not (i.e. insert a space after you moved the caret), you can set e.Handled in PreviewKeyDown to either true (don't do any more handling) or false (let the TextBox handle the space key, too).


Try the PreviewKeyDown event in stead of the KeyDown event, and set the KeyEventArgs e.Handled property to true!

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜