【问题标题】:(WinRT)How to get TextBox caret index?(WinRT)如何获取文本框插入符号索引?
【发布时间】:2015-10-23 23:25:41
【问题描述】:


在 Windows Store App(WP 8.1)中获取 TextBox 的插入符号索引时遇到了一些问题。
按下按钮时,我需要在文本中插入特定符号。 我试过这个:

 text.Text = text.Text.Insert(text.SelectionStart, "~");



但是此代码将符号插入文本的开头,而不是插入符号所在的位置。

更新

感谢Ladi,我更新了我的代码。但现在我遇到了另一个问题:我正在构建 HMTL 编辑器应用程序,所以我的默认 TextBlock.Text 是:

    <!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n</body>\r\n</html>

因此,例如,当用户将符号插入第 3 行时,符号会在插入符号前插入 2 个符号;插入符号在第 4 行之前的 3 个符号,依此类推。将符号插入第一行时,插入工作正常。

这是我的插入代码:
Index = HTMLBox.SelectionStart;
HTMLBox.Text = HTMLBox.Text.Insert(Index, (sender as AppBarButton).Label);
HTMLBox.Focus(Windows.UI.Xaml.FocusState.Keyboard);
HTMLBox.Select(Index+1,0);


那么如何解决呢?
我猜换行符会惹麻烦。

【问题讨论】:

  • 您的代码有效(我刚刚检查过)。在尝试访问 text.SelectionStart 之前,您是否有机会更改文本?因为如果你这样做,当你设置 text.Text 时,text.SelectionStart 将被重置为 0。
  • @Ladi 请查看更新

标签: c# xaml windows-runtime windows-phone-8.1 winrt-xaml


【解决方案1】:

对于您的第一个问题,我假设您在访问 SelectionStart 之前更改了 TextBox.Text。当你设置text.Text时,text.SelectionStart被重置为0。

关于您与新行相关的第二个问题。

您可以说您所观察到的是设计使然。 SelectionStart 将一个“\r\n”计为一个字符,原因解释为here(参见备注部分)。另一方面,方法string.Insert 不关心该方面并将“\r\n”计为两个字符。

您需要稍微更改您的代码。您不能使用SelectionStart 的值作为插入位置。您需要计算 SelectionStart 的这种行为的插入位置。

这是一个带有潜在解决方案的详细代码示例。

// normalizedText will allow you to separate the text before 
// the caret even without knowing how many new line characters you have.
string normalizedText = text.Text.Replace("\r\n", "\n");
string textBeforeCaret = normalizedText.Substring(0, text.SelectionStart);

// Now that you have the text before the caret you can count the new lines.
// that need to be accounted for.
int newLineCount = textBeforeCaret.Count(c => c == '\n');

// Knowing the new lines you can calculate the insert position.
int insertPosition = text.SelectionStart + newLineCount;

text.Text = text.Text.Insert(insertPosition, "~"); 

您还应确保 SelectionStart 不会与“\r\n”之外的其他组合表现出类似的行为。如果是,则需要更新上面的代码。

【讨论】:

  • 非常感谢老兄!这真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 2010-09-06
  • 2012-03-06
  • 2011-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-20
相关资源
最近更新 更多