WPF TextBox - programatically select text while preserving "selection direction"
When editing text the user is able to use the keybord shift button and direction keys to modify the selection - one position stays anchored while the other moves. By pressing left it is possible to get the movable part on the left of the anchored part.
I'm trying to dinamicaly modify the users selection in WPF's TextBox (for the purpose of the discussion, lets say I want to select the characters in pairs, eg. 开发者_运维问答when pressing shift+left, 2 characters would get selected, not just one). However, when using SelectionStart/SelectionIndex/CaretIndex/Select the "movebale end" of the selection is always ends up on the far right end of the selection, rendering the shift+left combination useless.
Any way to preserve the "selection direction"?
This is not quite the answer you are looking for but it'll work. Invoke the command and do it the way WPF does it.
EditingCommands.SelectLeftByCharacter.Execute(null, textBox1);
None of those work. SelectionLength doesn't allowed to be negative, and CaretIndex is always identical to SelectionStart. This is a design bug in TB, as you cannot achieve a valid state of it even in the protected scope.
The command actually works, but you still cannot determine the selection's direction of the currently analyzed textbox. There's only one solution, which is an ugly workaround: You can write your own observer code by overriding the mouse and keyboard event handlers.
The only possibility I can think of is to set the SelectionStart and then make the SelectionLength negative.
Have you tried setting the CaretIndex property before or after setting SelectionStart/SelectionLength?
精彩评论