Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lawrence_shaun_introducing_net_maui_build_and_deploy_crosspl.pdf
Скачиваний:
46
Добавлен:
26.06.2023
Размер:
5.15 Mб
Скачать

Chapter 4 An Architecture to Suit You

The above code should be familiar. You saw it when reviewing MVVM. The optimization made here is to reduce the size of the Time property down to just 5 lines where the original example was 16 lines of code.

Adding Views

First, add a new folder to your project.

•\

Right-click the WidgetBoard project.

•\

Select Add New Folder.

•\

Enter the name Views.

•\

Click Add.

This folder will house your application’s views. Let’s proceed to adding your first one.

Adding IWidgetView

The first item you need to add is an interface to represent all widget view models that you create in your application.

•\

Right-click the Views folder.

•\

Select Add New Item.

•\

Select the Interface type.

•\

Enter the name IWidgetView.

•\

Click Add.

96

Chapter 4 An Architecture to Suit You

Modify the contents of this file to the following:

using WidgetBoard.ViewModels;

namespace WidgetBoard.Views;

public interface IWidgetView

{

int Position { get => WidgetViewModel.Position; set => WidgetViewModel.Position = value; }

IWidgetViewModel WidgetViewModel { get; set; }

}

Adding ClockWidgetView

The next item you need to add is a ContentView. This is the first time you are doing this, so use the following steps:

•\

Right-click the Views folder.

•\

Select Add New Item.

•\

Select the .NET MAUI tab.

•\

Select the .NET MAUI ContentView (XAML) option.

•\

Enter the name ClockWidgetView.

•\

Click Add.

Observe that two new files have been added to your project:

ClockWidgetView.xaml and ClockWidgetView.xaml.cs. You may notice that the ClockWidgetView.xaml.cs file is hidden in the Solution Explorer panel and that you need to expand the arrow to the left of the

ClockWidgetView.xaml file.

Let’s update both files to match what was in the original examples.

97

Chapter 4 An Architecture to Suit You

Open the ClockWidgetView.xaml file and modify the contents to the following:

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

xmlns="http://schemas.microsoft.com/dotnet/2021/maui"

xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:viewmodels="clr-namespace:WidgetBoard.ViewModels" x:Class="WidgetBoard.Views.ClockWidgetView"

FontSize="60"

VerticalOptions="Center"

HorizontalOptions="Center"

x:DataType="viewmodels:ClockWidgetViewModel" Text="{Binding Time}">

</Label>

Open the ClockWidgetView.xaml.cs file and modify the contents to the following:

using WidgetBoard.ViewModels;

namespace WidgetBoard.Views;

public partial class ClockWidgetView : Label, IWidgetView

{

public ClockWidgetView()

{

InitializeComponent();

WidgetViewModel = new ClockWidgetViewModel(); BindingContext = WidgetViewModel;

}

public IWidgetViewModel WidgetViewModel { get; set; }

}

98