Add hyperlink to textblock wpf

You can use Regex with a value converter in such situation.

Use this for your requirements (original idea from here):

    private Regex regex = 
        new Regex(@"\[a\s+href='(?<link>[^']+)'\](?<text>.*?)\[/a\]",
        RegexOptions.Compiled);

This will match all links in your string containing links, and make 2 named groups for each match : link and text

Now you can iterate through all the matches. Each match will give you a

    foreach (Match match in regex.Matches(stringContainingLinks))
    { 
        string link    = match.Groups["link"].Value;
        int link_start = match.Groups["link"].Index;
        int link_end   = match.Groups["link"].Index + link.Length;

        string text    = match.Groups["text"].Value;
        int text_start = match.Groups["text"].Index;
        int text_end   = match.Groups["text"].Index + text.Length;

        // do whatever you want with stringContainingLinks.
        // In particular, remove whole `match` ie [a href='...']...[/a]
        // and instead put HyperLink with `NavigateUri = link` and
        // `Inlines.Add(text)` 
        // See the answer by Stanislav Kniazev for how to do this
    }

Note : use this logic in your custom ConvertToHyperlinkedText value converter.


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

<TextBlock Name="TextBlockWithHyperlink">
    Some text
    <Hyperlink
        NavigateUri="http://somesite.example"
        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());
}

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.example")
};
hyperLink.Inlines.Add("some site");
hyperLink.RequestNavigate += Hyperlink_RequestNavigate;
TextBlockWithHyperlink.Inlines.Add(hyperLink);
TextBlockWithHyperlink.Inlines.Add(" Some more text");