Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add hyperlink to textblock wpf

Greetings, I have some text in a db and it is as follows:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tellus nisl, venenatis et pharetra ac, tempor sed sapien. Integer pellentesque blandit velit, in tempus urna semper sit amet. Duis mollis, libero ut consectetur interdum, massa tellus posuere nisi, eu aliquet elit lacus nec erat. Praesent a commodo quam. **[a href='http://somesite.com']some site[/a]**Suspendisse at nisi sit amet massa molestie gravida feugiat ac sem. Phasellus ac mauris ipsum, vel auctor odio

My question is: How can I display a Hyperlink in a TextBlock? I don't want to use a webBrowser control for this purpose. I don't want to use this control either: http://www.codeproject.com/KB/WPF/htmltextblock.aspx also

like image 860
niao Avatar asked Jan 19 '10 10:01

niao


People also ask

How do you hyperlink in XAML?

The hyperlink is the TextBlock content. TextBlock tb = new TextBlock(); // Create a Hyperlink and a Run. // The Run provides the visible content of the hyperlink. Hyperlink hyperlink = new Hyperlink(); Run run = new Run(); // Set the Text property on the Run. This will be the visible text of the hyperlink.

What is TextBlock WPF?

The TextBlock control provides flexible text support for UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize, FontWeight, TextEffects, and TextWrapping.


1 Answers

Displaying is rather simple, the navigation is another question. XAML goes like this:

<TextBlock Name="TextBlockWithHyperlink">     Some text      <Hyperlink          NavigateUri="http://somesite.com"         RequestNavigate="Hyperlink_RequestNavigate">         some site     </Hyperlink>     some more text </TextBlock> 

And the event handler that launches default browser to navigate to your hyperlink would be:

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

Edit: To do it with the text you've got from database you'll have to parse the text somehow. Once you know the textual parts and hyperlinked parts, you can build textblock contents dynamically in the code:

TextBlockWithHyperlink.Inlines.Clear(); TextBlockWithHyperlink.Inlines.Add("Some text "); Hyperlink hyperLink = new Hyperlink() {     NavigateUri = new Uri("http://somesite.com") }; hyperLink.Inlines.Add("some site"); hyperLink.RequestNavigate += Hyperlink_RequestNavigate; TextBlockWithHyperlink.Inlines.Add(hyperLink); TextBlockWithHyperlink.Inlines.Add(" Some more text"); 
like image 66
Stanislav Kniazev Avatar answered Oct 05 '22 20:10

Stanislav Kniazev