我正在使用WPF构建桌面应用程序,并希望在浏览器中打开超链接。我可以通过在后面的代码中放入一个方法并从XAML中调用它来实现这一点,如下所示,但是如何从多个XAML页面调用此方法?
XAML
<Hyperlink NavigateUri="http://www.mylink.com" RequestNavigate="Hyperlink_RequestNavigate">My link text</Hyperlink>
C#
private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
答案 0 :(得分:3)
您可以将其设置为App.xaml
中的样式,例如
<Application.Resources>
<Style x:Key="LaunchLinkStyle" TargetType="{x:Type Hyperlink}">
<EventSetter Event="RequestNavigate" Handler="LaunchLinkStyle_RequestNavigate" />
</Style>
</Application.Resources>
(处理程序当然会在App.xaml.cs中实现)
然后您可以参考样式:
<Hyperlink Style="{StaticResource LaunchLinkStyle}" ... />
答案 1 :(得分:0)
谢谢H.B.你的答案让我走上了正确的道路。这是完整的代码:
在我的页面中:
<Hyperlink NavigateUri="http://www.mylink.com" Style="{StaticResource LaunchLinkStyle}">My Link</Hyperlink>
<强>的App.xaml 强>
<Style x:Key="LaunchLinkStyle" TargetType="{x:Type Hyperlink}">
<EventSetter Event="RequestNavigate" Handler="LaunchLinkStyle_RequestNavigate"/>
</Style>
<强> App.xaml.cs 强>
public void LaunchLinkStyle_RequestNavigate(object sender, RoutedEventArgs e)
{
/* Function loads URL in separate browser window. */
Hyperlink link = e.OriginalSource as Hyperlink;
Process.Start(link.NavigateUri.AbsoluteUri);
e.Handled = true; //Set this to true or the hyperlink loads in application and browser windows
}