13

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.

H.B.
  • 166,899
  • 29
  • 327
  • 400
PaulN
  • 329
  • 2
  • 6
  • 13

2 Answers2

11

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

H.B.
  • 166,899
  • 29
  • 327
  • 400
2

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());
}
Winter Dragoness
  • 1,327
  • 12
  • 13
Rocksn17
  • 739
  • 1
  • 9
  • 9