如何创建WebView和.NET MAUI中的网页的预览
#dotnet #csharp #ios #maui

第一句话

大家好!在本文中,我想向您展示如何创建网站的Web视图和预览的实例。请让自己舒适,喝茶或咖啡,让我们开始。

项目

让我们从模板创建一个新项目。

dotnet new maui -n WebViewSample

让我们直接清理MainPage。您应该在scrollview块中删除所有代码,并在类中删除还原代码,并且它应该仅是构造函数并初始化组件。

网站的预览

我将创建两个视图模型。第一个将是预览,第二个将是网络视图。您需要在项目的根部创建一个新文件夹。我们可以称呼此文件夹ViewModels.
在我们继续之前,让我们添加一个软件包。我想警告你,这不是必需的。否则,您需要编写更多代码。我希望您安装此CommunityToolkit.Mvvm包。执行此操作后,您应该创建一个名为MainPageViewModel的新类并粘贴此代码:

[ObservableObject]
public partial class MainPageViewModel
{
    public ICommand SelectionChangedCommand
    {
        get => new Command(async () => await GoToWebsiteDetails());
    }

    private ObservableCollection<WebSiteModel> _websiteList;

    public ObservableCollection<WebSiteModel> WebsiteList
    {
        get => _websiteList;
        set
        {
            _websiteList = value;
            OnPropertyChanged();
        }
    }

    private WebSiteModel _selectedWebsite;

    public WebSiteModel SelectedWebsite
    {
        get => _selectedWebsite;
        set => SetProperty(ref _selectedWebsite, value);
    }


    private async Task GoToWebsiteDetails()
    {
        if (SelectedWebsite == null)
        {
            return;
        }

        SelectedWebsite = null;
    }

    public MainPageViewModel()
    {
        WebsiteList = GetDataForList();
    }

    private ObservableCollection<WebSiteModel> GetDataForList()
    {
        return new ObservableCollection<WebSiteModel>
        {
            new()
            {
                Title = "Facebook",
                Description =
                    "Facebook is an online social media and social networking service owned by American technology giant Meta Platforms. ",
                Url = new Uri("https://facebook.com/")
            },
            new()
            {
                Title = "Amazon",
                Description =
                    "Amazon.com, Inc.[1] (/ˈæməzɒn/ AM-ə-zon UK also /ˈæməzən/ AM-ə-zən) is an American multinational technology company focusing on e-commerce, cloud computing, online advertising, digital streaming, and artificial intelligence.",
                Url = new Uri("https://www.amazon.com/")
            },
            new()
            {
                Title = "Apple Inc",
                Description =
                    "Apple Inc. is an American multinational technology company headquartered in Cupertino, California. Apple is the world's largest technology company by revenue, with US$394.3 billion in 2022 revenue.[6] Apple Inc. is an American multinational technology company headquartered in Cupertino, California. Apple is the world's largest technology company by revenue, with US$394.3 billion in 2022 revenue.[6] ",
                Url = new Uri("https://www.apple.com/")
            },
            new()
            {
                Title = "Netflix",
                Description =
                    "Netflix is an American subscription video on-demand over-the-top streaming television service owned and operated by Netflix, Inc., a company based in Los Gatos, California. ",
                Url = new Uri("https://www.netflix.com/")
            },
            new()
            {
                Title = "Google LLC",
                Description =
                    "Google LLC (/ˈɡuːɡəl/ (listen)) is an American multinational technology company focusing on artificial intelligence,[9] online advertising, search engine technology, cloud computing, computer software, quantum computing, e-commerce, and consumer electronics.",
                Url = new Uri("https://www.google.com/")
            },
        };
    }
}

我想解释这堂课在做什么。 WebsiteList集合是一个可观察到的集合,可检测变化状态。此SelectedWebsite属性设置了所选项目,而SelectionChangedCommand命令允许选择用于选择。 gotowebsitedEtails将重定向到以后将完成的另一个视图。构造函数设置了用于显示的数据。
此外,我们需要为每个站点创建一个模型。让我们创建一个新的型号文件夹并创建一个新的WebsItemodel Record。进入记录粘贴此代码:

public record WebSiteModel
{
    public Uri Url { get; set; }
    public string Description { get; set; }
    public string Title { get; set; }
}

下一步,转到MainPage类,然后注入创建的MainPageViewModel。应该这样:

public MainPage(MainPageViewModel mainPageViewModel)
    {
        InitializeComponent();
        BindingContext = mainPageViewModel;
    }

现在,转到此类的布局并粘贴此代码:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="WebViewSample.MainPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:models="clr-namespace:WebViewSample.Models"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

    <ScrollView>
        <VerticalStackLayout>
            <CollectionView
                ItemsSource="{Binding WebsiteList}"
                SelectedItem="{Binding SelectedWebsite}"
                SelectionChangedCommand="{Binding SelectionChangedCommand}"
                SelectionMode="Single">
                <CollectionView.ItemTemplate>
                    <DataTemplate x:DataType="models:WebSiteModel">
                        <StackLayout>
                            <Grid HorizontalOptions="Center" Margin="0,10,0,10">
                                <Label
                                    FontAttributes="Bold"
                                    FontSize="22"
                                    Text="{Binding Title}" />
                            </Grid>
                            <BoxView
                                Color="Black"
                                HeightRequest="1"
                                HorizontalOptions="FillAndExpand"
                                Margin="0,10,0,10" />
                            <Grid HorizontalOptions="Center">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto" />
                                    <ColumnDefinition Width="Auto" />
                                </Grid.ColumnDefinitions>
                                <Frame
                                    CornerRadius="20"
                                    Margin="10"
                                    Padding="5">
                                    <WebView
                                        HeightRequest="200"
                                        Source="{Binding Url}"
                                        WidthRequest="200" />
                                </Frame>
                            </Grid>
                            <Grid HorizontalOptions="Center" Margin="10">
                                <Border Stroke="#808080" StrokeThickness="3">
                                    <Border.StrokeShape>
                                        <RoundRectangle CornerRadius="10,10,10,10" />
                                    </Border.StrokeShape>
                                    <Label
                                        FontAttributes="Italic"
                                        FontSize="16"
                                        HorizontalTextAlignment="Center"
                                        LineBreakMode="WordWrap"
                                        Padding="15"
                                        Text="{Binding Description}" />
                                </Border>
                            </Grid>
                        </StackLayout>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>

我们在退房之前,让我们注册我们的ViewModel并查看。进入MauiProgram类并粘贴此代码:

builder.Services.AddSingleton<MainPage>();
builder.Services.AddSingleton<MainPageViewModel>();

如果一切正常,那么您将看到此页面:

Main page

您可以看到,每个元素都有一个可以滚动并单击不同元素的预览。

网络查看页面

遵循步骤,我们需要在ViewModels文件夹中创建一个新的WebViewPageViewModel类。该类更容易,并且处理选定的元素:

[ObservableObject]
public partial class WebViewPageViewModel
{

    private WebSiteModel _selected;
    public WebSiteModel Selected
    {
        get => _selected;
        set => SetProperty(ref _selected, value);
    }


    public WebViewPageViewModel(WebSiteModel selected)
    {
        _selected = selected;        
    }
}

此外,您应该创建一个名为WebViewPage的新内容页面,并添加一点代码:

public partial class WebViewPage : ContentPage
{
    public WebViewPage(WebSiteModel selectedSite)
    {
        InitializeComponent();
        BindingContext = new WebViewPageViewModel(selectedSite);
    }


    private void OnSwiped(object sender, SwipedEventArgs e)
    {
        if (e.Direction == SwipeDirection.Right)
        {
            Application.Current!.MainPage!.Navigation.PopAsync();
        }
    }

OnSwiped方法允许向后滑动到开始页面。视图也很简单:

<?xml version="1.0" encoding="utf-8" ?>

<ContentPage
    x:Class="WebViewSample.WebViewPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <Grid>
        <Grid.GestureRecognizers>
            <SwipeGestureRecognizer Direction="Right" Swiped="OnSwiped" />
        </Grid.GestureRecognizers>
        <WebView Source="{Binding Selected.Url}" />
    </Grid>
</ContentPage>

要完成这项工作,您应该返回MainPageViewModel并找到GoToWebsiteDetails方法,然后粘贴这一行:

await Application.Current!.MainPage!.Navigation.PushModalAsync(new WebViewPage(SelectedWebsite));

如果您正确地完成了所有操作,如果您可以按项目点击,则将重定向到网站。对于后背,就向右滑动。

Web view

综上所述

这就是我要展示的全部。您可以通过link找到来源。
愉快的编码!
Buy Me A Beer