'C# Hyperlink in TextBlock: nothing happens when I click on it

In my C# standalone application, I want to let users click on a link that would launch their favorite browser.

System.Windows.Controls.TextBlock text = new TextBlock();
Run run = new Run("Link Text");

Hyperlink link = new Hyperlink(run);
link.NavigateUri = new Uri("http://w3.org");
text.Inlines.Add(link);

The link is displayed correctly.

When I move the mouse over it, the link becomes red.

PROBLEM: When I click it, nothing happens.

Did I forget something? Do I need to implement some kind of method to really let the link be opened?



Solution 1:[1]

Are you handling the 'Hyperlink.RequestNavigate' event? When a user clicks a Hyperlink in a WPF window it doesn't automatically open a browser with the URI specified in its NavigateUri property.

In your code-behind you can do something like:

link.RequestNavigate += LinkOnRequestNavigate;

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

Solution 2:[2]

You can make a global hyperlink handler in your App.xaml.cs

protected override void OnStartup(StartupEventArgs e) {
    EventManager.RegisterClassHandler(
        typeof(System.Windows.Documents.Hyperlink),
        System.Windows.Documents.Hyperlink.RequestNavigateEvent,
        new System.Windows.Navigation.RequestNavigateEventHandler(
            (sender, en) => Process.Start(new ProcessStartInfo(
                en.Uri.ToString()
            ) { UseShellExecute = true })
        )
    );
    base.OnStartup(e);
}

This assumes all the NavigateUri properties refer to something you want to launch, but you can always make the handler take care of edge cases.

Solution 3:[3]

For those in .Net Core, the way you do this has changed. Based on this answer and this.

link.RequestNavigate += (sender, e) =>
{
    var url = e.Uri.ToString();
    Process.Start(new ProcessStartInfo(url)
    { 
        UseShellExecute = true 
    });
};

Solution 4:[4]

Working with a command is also possible:

<TextBlock>
    See our <Hyperlink NavigateUri="https://www.example.com" Command="{Binding OpenPrivacyPolicyCommand}">Privacy Policy</Hyperlink>
</TextBlock>

The command needs to call open the URL then:

Process.Start(url);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Kao
Solution 4 ndsvw