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
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With