在我的 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);
链接显示正确。
当我将鼠标移到它上面时,链接会变成红色。
问题:当我单击它时,没有任何反应。
我是不是忘记了什么?我是否需要实现某种方法才能真正让链接打开?
您需要处理超链接的
RequestNavigate
事件。这是一个快速的方法:
link.RequestNavigate += (sender, e) =>
{
System.Diagnostics.Process.Start(e.Uri.ToString());
};
您正在处理“Hyperlink.RequestNavigate”事件吗?当用户单击 WPF 窗口中的超链接时,它不会自动打开具有 NavigateUri 属性中指定的 URI 的浏览器。
在您的代码隐藏中,您可以执行以下操作:
link.RequestNavigate += LinkOnRequestNavigate;
private void LinkOnRequestNavigate(object sender, RequestNavigateEventArgs e)
{
System.Diagnostics.Process.Start(e.Uri.ToString());
}
您可以在 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);
}
这假设所有 NavigateUri 属性都引用您想要启动的内容,但您始终可以让处理程序处理边缘情况。
也可以使用命令:
<TextBlock>
See our <Hyperlink NavigateUri="https://www.example.com" Command="{Binding OpenPrivacyPolicyCommand}">Privacy Policy</Hyperlink>
</TextBlock>
该命令需要调用打开URL然后:
Process.Start(url);
使用MVVM时
在您的.xaml中
<TextBlock>
<Run Text="Gold buyers " /><Hyperlink Command="{Binding ViewGoldBuyersGuideCommand}" ><Run Text="guide" /></Hyperlink>
</TextBlock>
在你的 vm.cs 文件中
public ICommand ViewGoldBuyersGuideCommand { get; private set; }
ViewGoldBuyersGuideCommand = new DelegateCommand<object>(OnViewGoldBuyersGuide); // inside your constructor
private void OnViewGoldBuyersGuide(object obj)
{
Process.Start("https://example.com/");
}