简体   繁体   中英

How do I work with keyboard shortcuts in WPF?

I have 10 check box items sorted alphabetically, say for example:

Apple, AirCraft, Ball, Bottom, Cat, etc.

By pressing the A key the focus must be set to the Apple check box, B - to Ball . How can I do this? These check box items are dynamically variable due to the item source count.

Since checkbox items are not hardcoded in XAML I cannot tag, I guess; I load them during run time. And what if I have items like the following?

  1. Apple
  2. Apple1
  3. Apple2

In this scenario I can't set the shortcut right, so instead, if I press A the first item that starts with letter A will get focus and again pressing A , focus set to the next item that starts with letter A . If it reaches the last item that starts with letter A then again if I press A it has to go to the first item that has starting letter A , so this is my requirement:). How can I do this?

You can use the keyboard navigation by first pressing the alt key, and setting the check boxes content as:

<CheckBox Content="_Apple" />
<CheckBox Content="_Ball" />

Keep in mind that the associated keyboard shortcut will be the one after the "_" symbol.

It's very simple to traverse items:

By pressing the A key, the focus must be set to the Apple check box, B - to Ball . These check box items are dynamically variable due to the item source count.

Just do it as below. Place the underscore symbol, "_" , before "A" :

  1. _Apple
  2. _Apple1
  3. _Apple2

If I press A the first item that starts with letter A will get focus and again pressing A focus is set to the next item that starts with letter A . If it reaches the last item starts with letter A then again if I press A it will go to the first item that has starting letter A . If you want to check the checkbox you can use the SpaceBar . Provided checkbox items must be within ItemsControl.

You'll need to come up with some set of rules as to what key press results in which item - ie, if there are two "A" items, what item is selected on "A"?

Then you'll have to manually find the item that matches the entered keypress on a keypress and highlight it.

Subscribe to the OnPreviewKeyDown event of the container which holds your CheckBox items. Then implement what happens when a specific button is pressed.

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