xamarin - WebView.Navigated 和 ViewModel

标签 xamarin xamarin.forms prism

在 View Model 中使用 Prism 时,是否可以在 Xamarin Form 中捕获 WebView 控件的导航事件?我的控件定义如下所示

<WebView Source="{Binding GatewayPageSource,Mode=TwoWay}" WidthRequest="500" HeightRequest="500" />

最佳答案

WebView 对 MVVM 不是特别友好,因为它没有内置命令。不过,有几种方法可以解决这个问题。

1) 将 WebView 扩展为自定义控件,其中包括与您希望处理的事件关联的命令的 BindableProperties。类似如下。

public class MvvmWebView : WebView
{
    public static readonly BindableProperty NavigatingCommandProperty =
        BindableProperty.Create( nameof( NavigatingCommand ), typeof( ICommand ), typeof( MvvmWebView ), null );

    public static readonly BindableProperty NavigatedCommandProperty =
        BindableProperty.Create( nameof( NavigatedCommand ), typeof( ICommand ), typeof( MvvmWebView ), null );

    public MvvmWebView()
    {
        Navigating += ( s, e ) =>
        {
            if( NavigatingCommand?.CanExecute( e ) ?? false )
                NavigatingCommand.Execute( e );
        };

        Navigated += ( s, e ) => {
            if( NavigatedCommand?.CanExecute( e ) ?? false )
                NavigatedCommand.Execute( e );
        }
    }

    public ICommand NavigatingCommand
    {
        get { return ( ICommand )GetValue( NavigatingCommandProperty ); }
        set { SetValue( NavigatingCommandProperty, value ); }
    }

    public ICommand NavigatedCommand
    {
        get { return ( ICommand )GetValue( NavigatedCommandProperty ); }
        set { SetValue( NavigatedCommandProperty, value ); }
    }
}

2) 您可以向 WebView 添加类似于来自 Xamarin 的博客文章的行为正如已经提到的。还值得注意的是,Prism Forms 6.3.0-pre2 将与 EventToCommandBehavior 一起提供。 ,并且应该很快就会可用。

关于xamarin - WebView.Navigated 和 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42443884/

相关文章:

c# - Xamarin Forms 中没有 WebClient 类

c# - Prism 如何将模块 View 绑定(bind)到应用程序范围的属性

c# - 如何使用 PRISM 获取区域中的当前事件 View ?

c# - 获取当前 ViewModel MvvmCross

android - CoordinatorLayout 留空底部空间

android - 在实际设备上运行应用程序时出现问题

c# - GestureRecognizer 不适用于 ios xamarin.forms

c# - Shared Xamarin.Forms - 命名空间中不存在类型或命名空间名称 'App'

c# - Xamarin : Open page from string

wpf - 在 MVVM 中,拖动完成后打开上下文菜单