How to call method in a different namespace from XAML
I am building a desktop application with WPF and w开发者_JS百科ant to open a hyperlink in a browser. I can do this by putting a method in the code behind and calling it from the XAML as follows, but how can I call this method from multiple XAML pages?
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;
}
You could put this into a style in App.xaml
, e.g.
<Application.Resources>
<Style x:Key="LaunchLinkStyle" TargetType="{x:Type Hyperlink}">
<EventSetter Event="RequestNavigate" Handler="LaunchLinkStyle_RequestNavigate" />
</Style>
</Application.Resources>
(The handler then of course would be implemented in App.xaml.cs)
You then can just reference the style:
<Hyperlink Style="{StaticResource LaunchLinkStyle}" ... />
Thanks H.B. Your answer set me on the right path. Here's the complete code:
In my page:
<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
}
精彩评论