【问题标题】:Xamarin.Forms: how to access to the "Reload" method of a WebView from a ViewModelXamarin.Forms:如何从 ViewModel 访问 WebView 的“重新加载”方法
【发布时间】:2020-12-26 20:38:54
【问题描述】:

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

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

我想使用 ToolbarItem 来重置/重新加载 WebView

我可以在 代码隐藏 中实现这一点:

this.webView.Reload();

但我不知道如何在 ViewModel 中使用命令。可以这样做吗?

【问题讨论】:

  • VM 应该引发视图订阅的事件。
  • 谢谢@Jason,我该怎么做?
  • 现有数千篇关于在 C# 中创建自定义事件的帖子
  • 我不确定你的建议是什么。它与行为有关吗?
  • 不,只是基本的 C# 事件。但是,您也可以让您的工具栏项直接调用 WebView Refresh,而不涉及 VM。

标签: mvvm xamarin.forms webview command code-behind


【解决方案1】:

您可以在ToolbarItem中使用Command我的CommandParameter来实现它。

<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。

【讨论】:

  • 寻求实现类似的目标。这不是违反 MVVM 原则吗?我觉得 ViewModel 不应该调用任何 webview 方法,如 .Reload
猜你喜欢
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-29
  • 2020-02-24
  • 1970-01-01
相关资源
最近更新 更多