0

我想用我的 RichTextBox 中的超链接替换常规链接,所有信息都是通过外部库 (LinkEntity) 提供给我的。但我不知道如何实际替换文本。

我有这个,但它不能正常工作,有时它会抛出一个 value cannot be null 异常,有时它只是替换了链接的错误部分。

        Dim Start As TextPointer = TweetText.Document.ContentStart
        Dim StartPos As TextPointer = Start.GetPositionAtOffset(LinkEntity.StartIndex)
        Dim EndPos As TextPointer = Start.GetPositionAtOffset(LinkEntity.EndIndex)
        Dim h As New Hyperlink(StartPos, EndPos)
        AddHandler h.MouseLeftButtonDown, AddressOf Hyperclick_Link
        h.NavigateUri = New Uri(LinkEntity.Url)
        h.Cursor = Cursors.Hand

抛出异常是因为 StartPos 和 EndPos 什么都不是,即使 Start 和 End 索引具有有效值。

4

1 回答 1

1

我发现了问题,当我在声明 StartPos 和 EndPos 时调用它时,TweetText.Document 没有值。我的最终代码如下所示:

Dim FlowDocument As New FlowDocument
Dim Paragraph As New Paragraph
Paragraph.Inlines.Add(myfireactions.FormatTweet(Tweet))
FlowDocument.Blocks.Add(Paragraph)

Dim Start As TextPointer = FlowDocument.ContentStart
Dim StartPos As TextPointer = Start.GetPositionAtOffset(LinkEntity.StartIndex + 2)
Dim EndIndexInt As Integer = LinkEntity.StartIndex + LinkEntity.DisplayUrl.Length + 2
Dim EndPos As TextPointer = Start.GetPositionAtOffset(EndIndexInt, LogicalDirection.Backward)
Dim h As New Hyperlink(StartPos, EndPos)
AddHandler h.MouseLeftButtonDown, AddressOf Hyperclick_Link
h.NavigateUri = New Uri(LinkEntity.Url)
h.Cursor = Cursors.Hand

TweetText.Document = FlowDocument
于 2012-04-29T21:45:05.207 回答