Xamarin.Forms: 如何从 ViewModel 访问 WebView 的 "Reload" 方法

Xamarin.Forms: how to access to the "Reload" method of a WebView from a ViewModel

我正在开发一个 Xamarin.Forms 应用程序,其中包含一个 WebView 允许用户安排约会:

<WebView x:Name="webView" Source="{Binding UrlBooking}" WidthRequest="1000" HeightRequest="1000" /> 

我想使用 ToolbarItem 到 reset/reload WebView

我能够在代码隐藏中实现这一点:

this.webView.Reload();

但我看不出如何使用 ViewModel 中的命令执行此操作。可以这样做吗?

你可以用Command我的CommandParameterToolbarItem中实现。

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyCusListview.ToolbarItemPage">
    <ContentPage.ToolbarItems>
        <ToolbarItem Text="reload"
                 Command="{Binding ReloadWebview}"
                 CommandParameter="{Binding Source={x:Reference webView}}"
                 Order="Primary"
                 Priority="0" />
    </ContentPage.ToolbarItems>
    <ContentPage.Content>
        <StackLayout>
            <WebView Source="https://www.google.com/" x:Name="webView" WidthRequest="1000" HeightRequest="1000" ></WebView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

这里是布局背景代码。

 public partial class ToolbarItemPage : ContentPage
    {
        public ToolbarItemPage()
        {
            InitializeComponent();
            this.BindingContext = new PersonsViewModel();
        }
    }

这里是PersonsViewModel.cs,添加ICommand,在PersonsViewModel的构造函数中实现。

 public ICommand ReloadWebview { protected set; get; }

 public PersonsViewModel()
{
            ReloadWebview = new Command<WebView>((key) =>
            {
                key.Reload();


            });
}

这是运行 GIF。