【问题标题】:How do I get the start and end index from a selection inside RichTextBox?如何从 RichTextBox 中的选择中获取开始和结束索引?
【发布时间】:2018-05-09 03:31:31
【问题描述】:

我有一个富文本框,允许用户突出显示文本。正在加载的文本来自一个简单的纯文本文件。但我需要存储突出显示文本的绝对开始和结束字符位置(相对于文档开头),以便在保存时可以重新加载突出显示。

到目前为止,我可以这样做来应用突出显示

    private void textBox_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        HighlightWordInTextBox(this.textBox, this.textBox.Selection.ToString(), new SolidColorBrush(Colors.Yellow));
    }

    public void HighlightWordInTextBox(RichTextBox textbox, string word, SolidColorBrush color)
    {
        TextRange tr = new TextRange(this.textBox.Selection.Start, this.textBox.Selection.End);
        tr.ApplyPropertyValue(TextElement.BackgroundProperty, color);

    }

但我在选择的开始或结束对象内的任何地方都看不到任何提供字符位置的东西?几乎所有方法都返回另一个 TextPointer - 但是如何从 TextPointer 中获取字符位置?

假设所有文本都加载到单个

   this.textBox.Document.Blocks.Add(new Paragraph(new Run(fullText)));

编辑:

在调试时的即时窗口中,我可以访问名为 CharOffset 和 Offset 的内容,但不能在源代码中这样做,它会给出编译错误。这些属性虽然在运行时检查对象时存在,但它们不在文档中。

然而……

【问题讨论】:

标签: c# wpf


【解决方案1】:

你可以用这个找到Selection的开始和结束的索引...

        var docStart = textBox.Document.ContentStart;

        var selectionStart = textBox.Selection.Start;
        var selectionEnd = textBox.Selection.End;

        //these will give you the positions needed to apply highlighting
        var indexStart = docStart.GetOffsetToPosition(selectionStart);
        var indexEnd = docStart.GetOffsetToPosition(selectionEnd);

        //these values will give you the absolute character positions relative to the very beginning of the text.
        TextRange start = new TextRange(docStart, selectionStart);
        TextRange end = new TextRange(docStart, selectionEnd);
        int indexStart_abs = start.Text.Length;
        int indexEnd_abs = end.Text.Length;

【讨论】:

  • 为什么是负2?
  • @erotavlas 老实说,我不完全确定。但是,我对其进行了多次测试,指数为负 2。
  • 我认为您不需要 2 的偏移量。根据您对我的另一个问题的回答,它前面没有字符。 stackoverflow.com/q/50158510/1462656
  • @erotavlas 我接受了您的编辑。现在这是否完全回答了您的问题?
  • 实际上这并没有按预期工作stackoverflow.com/q/50237312/1462656
猜你喜欢
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 2018-08-01
  • 2019-07-17
  • 1970-01-01
  • 2017-11-03
相关资源
最近更新 更多