我的应用程序有一个用于显示一些联系信息的 WebView。它有一个指向我想要使用 Device.OpenUri()
从外部加载的网站的链接。我正在使用FreshMvvm我想拦截 ViewModel 中 WebView 的 Navigating
事件,并取消将外部页面加载到 WebView 中的默认操作。
我尝试过使用Corcav.Behaviors调用我的 ViewModel 命令的插件:
<WebView
HorizontalOptions="Fill"
VerticalOptions="FillAndExpand"
Source="{Binding WebViewSource}">
<b:Interaction.Behaviors>
<b:BehaviorCollection>
<b:EventToCommand
EventName="Navigating"
Command="{Binding NavigatingCommand}"
CommandParameter="{Binding}"/> <!-- what goes here -->
</b:BehaviorCollection>
</b:Interaction.Behaviors>
</WebView>
但我不确定 CommandParameter 应该是什么 - 我需要被点击的链接的 URI,并且我不知道如何防止发生默认行为。
这是最好的方法还是我应该寻找替代方法?
最佳答案
最近在另一个项目中重新审视了这一点,我偶然发现了 the answer 。更新后的 XAML 为:
<WebView
x:Name="webView"
HorizontalOptions="Fill"
VerticalOptions="FillAndExpand"
Source="{Binding WebViewSource}">
<behaviors:Interaction.Behaviors>
<behaviors:BehaviorCollection>
<behaviors:EventToCommand
EventName="Navigating"
Command="{Binding NavigatingCommand}"
PassEventArgument="True" />
</behaviors:BehaviorCollection>
</behaviors:Interaction.Behaviors>
</WebView>
在设备浏览器中打开链接之前,ViewModel 中的代码将点击的 URL 与有效选项列表进行匹配,如下所示:
public Command<WebNavigatingEventArgs> NavigatingCommand
{
get
{
return navigatingCommand ?? (navigatingCommand = new Command<WebNavigatingEventArgs>(
(param) =>
{
if (param != null && -1 < Array.IndexOf(_uris, param.Url))
{
Device.OpenUri(new Uri(param.Url));
param.Cancel = true;
}
},
(param) => true
));
}
}
关于xamarin.forms - 如何拦截ViewModel中的WebView导航事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36560415/