Note that there are some explanatory texts on larger screens.

plurals
  1. POWinRT XAML Textbox, SelectionStart and CR/LF
    primarykey
    data
    text
    <p>I am using a simple multiline <code>TextBox</code> in one of my <code>Windows Store Apps</code> and I would like to enable use of <code>tab</code> to indent the text.</p> <p>Since WinRT doesn't have the XAML <code>AcceptsTab</code> property on the <code>TextBox</code> I figured I'd have to handle it per hand when I detect the Tab keystroke.</p> <p><strong>The problem is: <code>\r\n</code> seems to be handled as one character instead of two by the SelectionStart property and I don't get the real <code>char</code> position.</strong></p> <p>The only idea I have right now is to normalize the <code>SelectionStart</code> by parsing the text and adding 1 to the <code>SelectionStart</code> for each of the <code>\r\n</code> occurences I see before the caret.</p> <pre><code>public static class TextBoxExtension { public static int GetNormalizedSelectionStart(this TextBox textBox) { int occurences = 0; string source = textBox.Text; for (var index = 0; index &lt; textBox.SelectionStart + occurences ; index++) { if (source[index] == '\r' &amp;&amp; source[index + 1] == '\n') occurences++; } return textBox.SelectionStart + occurences; } } </code></pre> <p>Finally the <code>SelectionStart</code> gets reseted to 0 after the manipulation, so I have to set it back to the correct position, this time using the non normalized position. Here's the caller:</p> <pre><code>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; } </code></pre> <p>It works but... have I reinvented that round thing again? Is there a cleaner way to do this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload