PaulN
PaulN

Reputation: 339

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.

Upvotes: 13

Views: 13420

Answers (2)

Rocksn17
Rocksn17

Reputation: 769

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

Upvotes: 3

brunnerh
brunnerh

Reputation: 184476

The Document in a RichTextBox is disabled by default, set RichtTextBox.IsDocumentEnabled to true.

Upvotes: 11

Related Questions