Remove hidden characters in WPF rich text box

(Since this question has not been getting any answers, I've re-worded it)

In my application, I have a dialog that holds a Rich Text Box, the box is filled with a Tweet gathered from Twitter. Using the tweet entities I format the tweet to have in-line hyperlinks to links in the tweet, mentions, and hashtags. However, the hyperlinks are never positioned correctly; always being 2 or 3 characters too soon and too far.

This is the code I use to set the text in the Rich Text Box:

TweetText.Document.ContentEnd.InsertTextInRun(Status.Text)
Dim FlowDocument As FlowDocument = TweetText.Document
If LinkEntity.Count > 0 Then
            For Each Entity As Entities.TwitterUrlEntity In LinkEntity
                Dim Start As TextPointer = FlowDocument.ContentStart
                Dim StartPosition As TextPointer
                Dim EndPosition As TextPointer
                If Entity.StartIndex = 0 Then
                    StartPosition = Start.GetPositionAtOffset(Entity.StartIndex)
                Else
                    StartPosition = Start.GetPositionAtOffset(Entity.StartIndex)
                End If
                EndPosition = Start.GetPositionAtOffset(Entity.StartIndex + Entity.DisplayUrl.Length, LogicalDirection.Backward)
                Dim h As New Hyperlink(StartPosition, EndPosition)
                AddHandler h.MouseLeftButtonDown, AddressOf Hyperclick_Link
                h.NavigateUri = New Uri(Entity.Url)
                h.Cursor = Cursors.Hand
            Next
        End If
'I have the other entities here, they have very similar code'
TweetText.Document = FlowDocument

This is my Rich Text Box XAML:

<RichTextBox Name="TweetText" Margin="5" FontSize="14" BorderThickness="0" IsReadOnly="True" />

This is the output:

问题!

The tweet entity has proper indexes for each entity, but I do think the Rich Text Box has hidden characters that are causing this offset.


It is interesting no one answered this one, but I kind of get it because RichTextBoxes are very nasty to use. I'm currently having trouble with one, too.

So, you are right, RichTextBox does use hidden characters, but you shouldn't try to remove them, as they help it work the way it does. You need to count only the character symbols when indexing, not other invisible tags and symbols.

I'm not quite good with VB, but you should be able to go with for loop and increase your index only if YourTextPointer.GetPointerContext(LogicalDirection.Forward) is TextPointerContext.Text , otherwise, you just skip it.

That way your indexes will match the ones in text.

链接地址: http://www.djcxy.com/p/50520.html

上一篇: 使用WPF显示丰富的格式化文本

下一篇: 删除WPF富文本框中的隐藏字符