如何获取RichTextBox中选择的最后一行/段落?

时间:2019-05-22 13:41:12

标签: c# wpf richtextbox

我在RichTextBox中的选择中有一个奇怪的行为:

在完全选择了选择的最后一行的选择中,.End属性不是指向选择的最后一行(段落),而是指向下一段。 行为的屏幕截图:

所选文本

enter image description here

.Text属性显示正确的内容

enter image description here

但是.End属性指向以下paragraph

enter image description here

我可以遍历选择内容,并将.Text属性的内容与段落和…中的运行进行比较。但是,有没有更简单的方法来获得选择的最后一段呢?

1 个答案:

答案 0 :(得分:0)

最后,我找到了这种方式来获得选择中的最后一行。似乎可以工作。

// In my case "this" is the RichTextBox itself, because I work in a derived class from RichTextBox
Paragraph lastLineInSelection = this.Selection.End.Paragraph;
if (this.Selection.End.IsAtLineStartPosition)
{
    Block previousBlock = this.Selection.End.Paragraph.PreviousBlock;
    while (previousBlock is Paragraph == false && previousBlock != null)
        previousBlock = previousBlock.PreviousBlock;

    if (previousBlock != null)
        lastLineInSelection = (previousBlock as Paragraph);
}
相关问题