开发者

WPF Keyboard Remapping

I am trying to remap the input of a textbox. For example. If a user enters a N then I would like to change it to a 9. I thought it might be best to try and catch it in the PreviewKeyDown event although I will also need to process paste attempts (I can solve that bit I think).

Is PreviewKeyDown a go开发者_StackOverflow中文版od place to start? If so, how do I send the replacement key. I know that e.Handled = true will stop the original key being processed.

Thanks.


I would subclass the textbox and add the desired behavior. (An attached behavior is another option, but I like the derived class better.)

public class MyTextBox : TextBox
{
    protected override void OnPreviewKeyDown(KeyEventArgs e)
    {
        if (e.Key == Key.N)
        {
            e.Handled = true;
            Text += '9';

            // Setting Text annoyingly puts SelectionStart at 0
            this.SelectionStart = Text.Length;
        }
        else
        {
            base.OnPreviewKeyDown(e);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜