简体   繁体   中英

How to get the next line with TextPointer.GetLineStartPosition() in a RichTextBox

I'm trying to get the lines of the RichTextBox .

Here they show how to do it:
Using GetLineStartPosition to get the end of a line in WPF RichTextBox

But for whatever reason I always get null as the return of GetLineStartPosition(1) .

XAML

    <Grid>
        <StackPanel>
            <Button Height="40" Click="Button_Click"></Button>

            <RichTextBox x:Name="rtbEditor">
                <FlowDocument>
                    <Paragraph>Hello, world!
                        a
                        <LineBreak/>
                        b
                        <LineBreak/>
                        c
                        <LineBreak/>
                        d
                    </Paragraph>
                </FlowDocument>
            </RichTextBox>
        </StackPanel>
    </Grid>

Code

        public MainWindow()
        {
            InitializeComponent();

            rtbEditor.AppendText("testtext" + "\r");
            rtbEditor.AppendText("testtext" + "\r");
            rtbEditor.AppendText("testtext" + "\r");
            rtbEditor.AppendText("testtext" + "\r\n");
            rtbEditor.AppendText("testtext" + "\r\n");
            rtbEditor.AppendText("testtext" + "\r\n");
            rtbEditor.AppendText("testtext" + "\n");
            rtbEditor.AppendText("testtext" + "\n");
            rtbEditor.AppendText("testtext" + "\n");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            TextPointer contentStart = rtbEditor.Document.ContentStart;
            var nextStart = contentStart.GetLineStartPosition(1);
        }

nextStart is null . What am I doing wrong here?

This took a bit of research into how FlowDocument s and TextPointer s worked. I'd suggest reading the TextPointer Remarks Section because it really helped me understand this.

My theory is that the GetLineStartPosition method won't work if the current TextPointer doesn't have a Paragraph to reference. Document.ContentStart gives you a TextPointer that's just before the first Paragraph in the FlowDocument . You can call GetNextInsertionPosition(LogicalDirection.Forward) to return a TextPointer to the next valid insertion point- in this case the first valid insertion point- in the document. From there you are inside the first Paragraph and GetLineStartPosition starts to work.

TextPointer contentStart = rtbEditor.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward);
var nextStart = contentStart.GetLineStartPosition(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM