John Threepwood
John Threepwood

Reputation: 16143

How to add a hyperlink in a TextBlock in code?

In this question (the answer from eandersson) a hyperlink is used within a TextBlock. I would like to do the same but in the code behind - how to do that?

Example from the link:

<TextBlock>           
    <Hyperlink NavigateUri="http://www.google.com" RequestNavigate="Hyperlink_RequestNavigate">
        Click here
    </Hyperlink>
</TextBlock>

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
    e.Handled = true;
}

Upvotes: 3

Views: 5293

Answers (1)

Daniil Grankin
Daniil Grankin

Reputation: 3933

Here's the code to add a TextBlock with a clickable link in the middle :

Run run1 = new Run("click ");
Run run2 = new Run(" Please");
Run run3 = new Run("here.");

Hyperlink hyperlink = new Hyperlink(run3)
                       {
                           NavigateUri = new Uri("http://stackoverflow.com")
                       };
hyperlink.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(hyperlink_RequestNavigate); //to be implemented
textBlock1.Inlines.Clear();
textBlock1.Inlines.Add(run1);
textBlock1.Inlines.Add(hyperlink);
textBlock1.Inlines.Add(run2);

from programmatically make textblock with hyperlink in between text

The same way you can use for addidng text block to container.

Upvotes: 10

Related Questions