简体   繁体   中英

Dynamically adding hyperlinks to a RichTextBox

I'm trying to dynamically add some hyperlinks to a RichTextBox using WPF and C# but am not having much success. My code is summarised below:

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!");
}

When I run this the RichTextBox show the link but it is grey and I cannot click on it? Can someone please point out where I might be going wrong.

Thanks.

默认情况下禁用RichTextBoxDocument ,将RichtTextBox.IsDocumentEnabled设置为true

A simple solution for reading a richTextBox text and transforming it into a link:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM