动态添加到RichTextBox的超链接

时间:2012-02-14 14:55:34

标签: c# wpf hyperlink richtextbox

我正在尝试使用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会显示链接,但它是灰色的,我无法点击它?有人可以指出我可能会出错的地方。

感谢。

2 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:2)

阅读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());
}