I use a simple multi-line TextBox in one of my Windows Store Apps , and I would like to enable the use of tab for text indents.
Since WinRT does not have the XAML AcceptsTab on the TextBox , I decided that I would have to handle it by hand when I detect a Tab key.
The problem is this: \r\n apparently being treated as one character instead of two using the SelectionStart property, and I am not getting the actual char position.
The only idea I have right now is to normalize the SelectionStart by analyzing the text and adding 1 to the SelectionStart for each of the \r\n events that I see in front of the carriage.
public static class TextBoxExtension { public static int GetNormalizedSelectionStart(this TextBox textBox) { int occurences = 0; string source = textBox.Text; for (var index = 0; index < textBox.SelectionStart + occurences ; index++) { if (source[index] == '\r' && source[index + 1] == '\n') occurences++; } return textBox.SelectionStart + occurences; } }
Finally, the SelectionStart reset to 0 after the manipulation, so I have to return it to the correct position, this time using the abnormal position. Here's the caller:
if (e.Key == VirtualKey.Tab) { int cursorIndex = MainTextBox.SelectionStart; int cursorIndexNormalized = MainTextBox.GetNormalizedSelectionStart(); MainTextBox.Text = MainTextBox.Text.Insert(cursorIndexNormalized, "\t"); MainTextBox.SelectionStart = cursorIndex + 1; e.Handled = true; }
It works, but ... did I reinvent this thing again? Is there a cleaner way to do this?
source share