gpt4 book ai didi

xamarin - WebView.Navigated 和 ViewModel

转载 作者:行者123 更新时间:2023-12-01 08:23:51 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com