私はTextBox
自分の 1 つで単純な複数行を使用しており、テキストをインデントWindows Store Apps
するために使用できるようにしたいと考えています。tab
AcceptsTab
WinRT には XAMLプロパティがないTextBox
ため、Tab キーストロークを検出したときに手ごとに処理する必要があると考えました。
問題は\r\n
、SelectionStart プロパティによって 2 文字ではなく 1 文字として処理されているようで、実際のchar
位置を取得できないことです。
私が今持っている唯一のアイデアはSelectionStart
、テキストを解析し、キャレットの前に表示される出現SelectionStart
ごとに1 を追加することで、 を正規化することです。\r\n
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;
}
}
最後にSelectionStart
は操作後に 0 にリセットされるため、今度は正規化されていない位置を使用して正しい位置に戻す必要があります。呼び出し元は次のとおりです。
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;
}
それは機能しますが... 私はその丸いものをもう一度再発明しましたか? これを行うためのよりクリーンな方法はありますか?