【问题标题】:XAML: Hyperlink to another ViewPageXAML:超链接到另一个 ViewPage
【发布时间】:2024-01-30 01:55:02
【问题描述】:

我正在开发一个 WinRT 应用程序,并且想知道是否可以将超链接标记链接到 JavaScript 函数或能够使用 NavigateUri 调用视图页面?或者是否可以使用通过命令调用 JS 的交互触发器。

==更新== 我一直在测试从超链接到超链接按钮的不同 xaml 标记。 HyperlinkBut​​ton 似乎出现并且是可点击的。它只是似乎没有被调用的点击功能......

 <HyperlinkButton Grid.Row="1"  Click="__Title__.OnBuildingClick" Content="Buildingoo"/>


 <HyperlinkButton Grid.Row="1"  Click="__Title__.OnBuildingClick" Content="Buildingoo" ?
   <i:EventTrigger EventName="ClickHyperlink">
              <behaviors:EventToScriptBehavior Command="__Title__.OnBuildingClick" />
            </i:EventTrigger>
          </i:Interaction.Triggers>
    </HyperlinkButton>

这是我采取的两种方法。函数 onBuildingClick 只是一个警报消息,但它不会被调用..

【问题讨论】:

  • 为了给你正确的答案,你的 WinRT 应用是基于 Html5/javascript 的吗?
  • 按定义基于 XAML 的应用程序仅限于执行从 C# 或 C++ 编译的代码。 XAML 和 Javascript 之间唯一可能进行交互的地方是在使用 WebView 控件的 C#(或 C++)/XAML 应用程序中。这是你的意图吗?
  • 没错。我们有一个使用 xaml 和 js 的在线灵魂资源管理器。虽然它是用 c# 编程的

标签: javascript wpf xaml windows-runtime winrt-xaml


【解决方案1】:

假设 webView 有一个预定义的名称“currentWebView”:

<WebView x:Name="currentWebView" ... />

您可以使用其名称从代码隐藏中访问该控件,然后告诉 Web 视图按名称在 DOM 中搜索 javascript 函数,并在该函数存在时调用它。

要通过名称调用方法,您将使用 C# 方法“InvokeScript”并传递 2 个参数:

参数 1:Javascript 函数的名称

参数 2:按 Javascript 签名顺序以逗号分隔的参数列表

currentWebView.InvokeScript("nameOfFunction", "myFirstparam, secondParam, thridParam");

此外,为了让 XAML UI 响应 Javascript 事件,您的 Javascript 代码必须调用

nameOfFunction(param1, param2, param3){
    window.external.notify("This content will be accessible in the next steps NotifyEventArgs e.Value property.")
};

在最后一个连接从 C# 响应 Javascript 的能力中,您必须在 C# 代码隐藏中应用一个事件处理程序,以允许 XAML 被通知 WebControl 内部发生的事情

// In the Constructor / OnLoaded/ OnNaviagtedTo Event of the code behind
currentWebView.ScriptNotify +=  new NotifyEventHandler(currentWebView_ScriptNotify);

... then later in the class

private void currentWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
   //can access the value included in the notification 
   var notification = e.Value;
   someTextblock.Text = notification;
}

把它放在一起:

<HyperlinkButton x:Name="btnExecuteJavaScript" Grid.Row="1"  Click="btnExecuteJavaScript_Click" Content="Buildingoo"/>

public void btnExecuteJavaScript_Click(object sender, RoutedEventArgs e)
{
    currentWebView.InvokeScript("OnBuildingClick", "arbitraryParameter, mayNotBeNeeded");
}

【讨论】: