wpf TextBlock 中的 C# 超链接:单击它时没有任何反应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12742690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:40:18  来源:igfitidea点击:

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

c#wpfhyperlinktextblocknavigateuri

提问by Nicolas Raoul

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

在我的 C# 独立应用程序中,我想让用户点击一个链接来启动他们最喜欢的浏览器。

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?

我是不是忘记了什么?我是否需要实现某种方法才能真正打开链接?

回答by markmuetz

You need to handle the hyperlink's RequestNavigateevent. Here's a quick way of doing it:

您需要处理超链接的RequestNavigate事件。这是一个快速的方法:

link.RequestNavigate += (sender, e) =>
{
    System.Diagnostics.Process.Start(e.Uri.ToString());
};

回答by Simon

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.

您是否正在处理“Hyperlink.RequestNavigate”事件?当用户单击 WPF 窗口中的超链接时,它不会使用其 NavigateUri 属性中指定的 URI 自动打开浏览器。

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());
}