【问题标题】:How to call method in a different namespace from XAML如何从 XAML 调用不同命名空间中的方法
【发布时间】:2011-10-28 18:34:51
【问题描述】:

我正在使用 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;
    }

【问题讨论】:

    标签: c# wpf xaml methods


    【解决方案1】:

    您可以将其放入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}" ... />
    

    【讨论】:

      【解决方案2】:

      感谢 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
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-05
        • 1970-01-01
        • 2013-01-08
        • 1970-01-01
        • 2015-05-06
        • 2021-02-11
        • 2015-04-28
        • 2019-07-23
        相关资源
        最近更新 更多