向RichTextBox动态添加超链接

本文关键字:超链接 添加 动态 RichTextBox | 更新日期: 2023-09-27 18:24:39

我正在尝试使用WPF和C#向RichTextBox动态添加一些超链接,但没有取得多大成功。我的代码总结如下:

FlowDocument doc = new FlowDocument();
richTextBox1.Document = doc;
richTextBox1.IsReadOnly = true;
Paragraph para = new Paragraph();
doc.Blocks.Add(para);
Hyperlink link = new Hyperlink();
link.IsEnabled = true;
link.Inlines.Add("Hyperlink");
link.NavigateUri = new Uri("http://www.google.co.uk");
link.Click += new RoutedEventHandler(this.link_Click);
para.Inlines.Add(link);
....
protected void link_Click(object sender, RoutedEventArgs e) {
    MessageBox.Show("Clicked link!");
}

当我运行这个时,RichTextBox显示链接,但它是灰色的,我无法点击它?有人能指出我哪里可能出错吗。

谢谢。

向RichTextBox动态添加超链接

默认情况下,RichTextBox中的Document处于禁用状态,将RichtTextBox.IsDocumentEnabled设置为true

读取richTextBox文本并将其转换为链接的简单解决方案:

richTextBox.IsDocumentEnabled = true;
TextPointer t1 = richTextBox1.Document.ContentStart;
TextPointer t2 = richTextBox1.Document.ContentEnd;
TextRange tr = TextRange(t1,t2);
string URI = tr.Text;
Hyperlink link = new Hyperlink(t1, t2);
link.IsEnabled = true;
link.NavigateUri = new Uri(URI); 
link.RequestNavigate += new RequestNavigateEventHandler(link_RequestNavigate);

private void link_RequestNavigate(object sender,RequestNavigateEventArgs e)
{
    System.Diagnostics.Process.Start(e.Uri.AbsoluteUri.ToString());
}