Reputation: 1350
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?
Upvotes: 1
Views: 420
Reputation: 6724
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);
Upvotes: 1