WPF - Build a string of pressed keys using KeyDown in ListView
I have a listview with a dozen of rows binded to xml. I'd like to have a possibility to locate and position the cursor to a certain record. For example: I have a with these ID, Name, Value:
1, Johny, Cash, USA
2, Jean-Michel, Jarre, France
3, Jeanette, , USA
When I would type "Je", the SelectedRow would be positioned to ID 2. When I would type "Jeane", the SelectedRow would be positioned to ID 3. Simply I'd like to have a possibility to search and go to the proper record in the开发者_Go百科 listview. I started building the SearchString and at this point I got stuck:
The one and only possibility in WPF is to use the KeyDown event. Unfortunately, this event return a kind of Key, which I was not able to convert to a string. E.g. when I press "A", SearchString would be "A". When I continue typing "B", SearchString would be "AB" etc. When SelectedItem changes, SearchString will be set to String.Empty. No KeyCode or other useful property/method is available.
And here comes the head rubbing. How can I build the SearchString I need? When I tried e.Key.ToString(), I got really funny strings - e.g. for 0 on Numpad I get a Key "Numpad0", for "," I get "OemComma" etc. I was trying also the TryParse method to char, for key "3" I get a value of "#" etc, it only works flawlessly just for letter A through Z, for other keys TryParse returns false.
The one and only way how to solve this is to build a translation table with a very long kind of "case e.Key.ToString() of":
"A": SearchString = SearchString + "A";
"System", SearchString = SearchString + " ";
"Numpad0", SearchString = SearchString + "0";
"ArrowUp", do nothing
etc etc etc.
Isn't there a more clever and simple way to do this?? Or I just don't see the trees because of the forest?
Handle PreviewTextInput instead. Reference: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/3fcfbe53-2c72-4fec-a997-dc881d1de72a.
EDIT:
Note: The ListView (and ListBox also) internally handles the KeyDown event for some keys to perform selection and navigation. Below are the keys that are internally handled by the ListView:
Key.Space:
Key.Return:
Key.Prior:
Key.Next:
Key.End:
Key.Home:
Key.Left:
Key.Up:
Key.Right:
Key.Down:
Key.Space is of particular interest because when space is pressed on a ListView, the PreviewTextInput event will not get fired. So to complete your solution, you would have to also add a handler for the ListView.PreviewKeyDown event and check if the space key was pressed in order for you to append the correct whitespace text.
精彩评论