DEV Community

Cover image for How to create WebView and the preview of a web page in .NET MAUI
Serhii Korol
Serhii Korol

Posted on

How to create WebView and the preview of a web page in .NET MAUI

First words

Hello guys! In this article, I want to show you instances of how to create web views and previews of the sites. Please make yourself comfortable, take tea or coffee, and let's begin.

Project

Let's create a new project from the template.

dotnet new maui -n WebViewSample
Enter fullscreen mode Exit fullscreen mode

And let's straight clean up MainPage. You should delete all code in the ScrollView block and delete reductant code in the class, and it should be only the constructor and initialize component in it.

Preview of the sites

I'll create two view models. The first will be a preview, and the second will be a web view. You need to create a new folder at the project's root. We can call this folder ViewModels.
Before we continue, let's add one package. I want to warn you, and it's not necessary. Otherwise, you need to write much more code. I would like that you install this CommunityToolkit.Mvvm package. After you do this, you should create a new class named MainPageViewModel and paste this code:

[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/")
            },
        };
    }
}
Enter fullscreen mode Exit fullscreen mode

I want to explain what this class is doing. The WebsiteList collection is an observable collection that detects changing states. This SelectedWebsite property sets the selected item, and the SelectionChangedCommand command allows a tap for selecting. The GoToWebsiteDetails make redirects to another view that will be finished later. The constructor sets data for showing in view.
Further, we need to create a model for each site. Let's create a new Models folder and create a new WebSiteModel record. Into the record paste this code:

public record WebSiteModel
{
    public Uri Url { get; set; }
    public string Description { get; set; }
    public string Title { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Next step, go to the MainPage class and inject created MainPageViewModel. It should be like that:

public MainPage(MainPageViewModel mainPageViewModel)
    {
        InitializeComponent();
        BindingContext = mainPageViewModel;
    }
Enter fullscreen mode Exit fullscreen mode

And now, go to the layout of this class and paste this code:

<?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>
Enter fullscreen mode Exit fullscreen mode

Before we'll check out, let's register our ViewModel and View. Got to the MauiProgram class and paste this code:

builder.Services.AddSingleton<MainPage>();
builder.Services.AddSingleton<MainPageViewModel>();
Enter fullscreen mode Exit fullscreen mode

If everything is OK then you'll see this page:

Main page

As you can see, each element has a preview that you can scroll and click to different elements.

Web view page

Following the step, we need to create a new WebViewPageViewModel class in the ViewModels folder. This class is easier and it handles selected elements:

[ObservableObject]
public partial class WebViewPageViewModel
{

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


    public WebViewPageViewModel(WebSiteModel selected)
    {
        _selected = selected;        
    }
}
Enter fullscreen mode Exit fullscreen mode

Further, you should create a new content page named WebViewPage and add a little bit of code:

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();
        }
    }
Enter fullscreen mode Exit fullscreen mode

The OnSwiped method allows swiping right for the back to the start page. The view also very simple:

<?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>
Enter fullscreen mode Exit fullscreen mode

To make this work, you should return to MainPageViewModel and find the GoToWebsiteDetails method, and paste this row:

await Application.Current!.MainPage!.Navigation.PushModalAsync(new WebViewPage(SelectedWebsite));
Enter fullscreen mode Exit fullscreen mode

If you did everything properly, and if you'll tap by item, you'll be redirected to the website. For the back just swipe right.

Web view

In conclusion

That's all I wanted to show. You can find the source by link.
Happy coding!
Buy Me A Beer

Top comments (0)