WebView.Navigated和ViewModel

Anu*_*wan 2 prism xamarin xamarin.forms

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

<WebView Source="{Binding GatewayPageSource,Mode=TwoWay}" WidthRequest="500" HeightRequest="500" />
Run Code Online (Sandbox Code Playgroud)

Dan*_* S. 7

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 ); }
    }
}
Run Code Online (Sandbox Code Playgroud)

2)您可以向WebView添加类似于Xamarin的博客帖子的行为,如上所述.值得注意的是,Prism Forms 6.3.0-pre2将随EventToCommandBehavior一起提供,并且很快就会推出.