问题
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?
- Apple
- Apple1
- 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?
回答1:
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.
回答2:
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":
- _Apple
- _Apple1
- _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.
回答3:
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.
回答4:
Subscribe to the OnPreviewKeyDown
event of the container which holds your CheckBox items. Then implement what happens when a specific button is pressed.
来源:https://stackoverflow.com/questions/15246589/how-do-i-work-with-keyboard-shortcuts-in-wpf