【问题标题】:C# WPF error: System.Windows.Markup.XamlParseException: ''Failed to create a 'RequestNavigate' from the text 'Hyperlink_RequestNavigate'.'C# WPF 错误:System.Windows.Markup.XamlParseException:“无法从文本“Hyperlink_RequestNavigate”创建“RequestNavigate”。
【发布时间】:2022-01-18 07:11:33
【问题描述】:

我需要创建一个 WPF 应用程序,在其中显示从网站上抓取的文本。在每个新的一天,文本都会改变。然而,问题是这个文本包含超链接,我也需要刮掉它们。从这个意义上说,我正在抓取 innerHtml 并修改为对 XAML 可读。

假设我正在抓取这个 HTML:

<p>Click <a href="google.com"> here </a> !!</p>

我将其修改为对 XAML 可读,如下所示:

<TextBlock> Click <Hyperlink RequestNavigate=\"Hyperlink_RequestNavigate\" NavigateUri='https://www.google.com/'> here </Hyperlink> !!! </TextBlock>

我是怎么做到的?

public partial class MainWindow : Window
{    
    public MainWindow()
    {
        InitializeComponent();
        var str = " Click <Hyperlink RequestNavigate=\"Hyperlink_RequestNavigate\" NavigateUri='https://www.google.com/'> here </Hyperlink> !!! ";
        grid.Children.Add(CreateTextBlock(str));
    }

    public TextBlock CreateTextBlock(string inlines)
    {
        var xaml = "<TextBlock xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">"
            + inlines + "</TextBlock>";
        return XamlReader.Parse(xaml) as TextBlock;
    }

    public void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
    {
        Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) { UseShellExecute = true });
        e.Handled = true;
    }
}

到目前为止一切都很好,但是出现了上面的错误:

System.Windows.Markup.XamlParseException: ''未能创建一个 来自文本“Hyperlink_RequestNavigate”的“RequestNavigate”。 ArgumentException:无法绑定到目标方法,因为它的 签名与委托类型不兼容。

感谢您的帮助。

【问题讨论】:

  • 你能告诉我们Hyperlink_RequestNavigate吗?在旁注中,嵌入WebView 并加载 html 会更容易。

标签: c# html wpf hyperlink screen-scraping


【解决方案1】:

XamlReader.Parse 方法不支持事件处理程序,但您可以简单地从正在解析的 XAML 中删除 RequestNavigate="Hyperlink_RequestNavigate",并通过将路由事件的事件处理程序附加到 @987654324 来处理所有超链接的 RequestNavigate 事件@:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        var str = " Click <Hyperlink NavigateUri='https://www.google.com/'> here </Hyperlink> !!! ";
        grid.Children.Add(CreateTextBlock(str));
        grid.AddHandler(Hyperlink.RequestNavigateEvent, new RequestNavigateEventHandler(Hyperlink_RequestNavigate));
    }

    public TextBlock CreateTextBlock(string inlines)
    {
        var xaml = "<TextBlock xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">"
            + inlines + "</TextBlock>";
        return XamlReader.Parse(xaml) as TextBlock;
    }

    public void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
    {
        Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) { UseShellExecute = true });
        e.Handled = true;
    }
}

【讨论】:

  • 谢谢你救了我
猜你喜欢
  • 2017-03-06
  • 1970-01-01
  • 2018-04-19
  • 1970-01-01
  • 2018-09-27
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
相关资源
最近更新 更多