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

Chapter 4 An Architecture to Suit You

FontSize="80"

VerticalOptions="Center"

HorizontalOptions="Center" />

</ContentView>

C# (Code-Behind)

The following code will have already been created for you by the .NET MAUI template. It is included for reference.

namespace WidgetBoard;

public partial class ClockWidget : ContentView

{

public ClockWidget()

{

InitializeComponent();

}

}

The InitializeComponent method call above is essential when building XAML-based views. It results in the XAML being loaded and parsed into an instance of the controls that have been defined in the XAML file.

ViewModel

The ViewModel acts as the bridge between the View and the Model. You expose properties and commands on the ViewModel that the View will bind to. To make a comparison to building applications with just code-­ behind, we could state that properties basically map to references of controls and commands are events. A binding provides a mechanism for both the View and ViewModel to send and receive updates.

80

Chapter 4 An Architecture to Suit You

For your ViewModel to notify the View that a property has changed and therefore the View will refresh the value displayed on screen, you need to make use of the INotifyPropertyChanged interface. This offers a single PropertyChanged event that you must implement and ultimately raise when your data-bound value has changed. This is all handled by the XAML binding engine, which you will look at in much more detail in the

next chapter. Let’s create your ViewModel class and then break down what is going on.

public class ClockWidgetViewModel : INotifyPropertyChanged

{

public event PropertyChangedEventHandler PropertyChanged;

private readonly Scheduler scheduler = new(); private DateTime time;

public DateTime Time

{

get

{

return time;

}

set

{

if (time != value)

{

time = value;

PropertyChanged?.Invoke(this, new PropertyChang edEventArgs(nameof(Time)));

}

}

81

Chapter 4 An Architecture to Suit You

}

public ClockWigetViewModel()

{

SetTime(DateTime.Now);

}

public void SetTime(DateTime dateTime)

{

Time = dateTime;

scheduler.ScheduleAction(

 

TimeSpan.FromSeconds(1),

 

() => SetTime(DateTime.Now));

}

 

}

 

You have

•\

Created a class called ClockWidgetViewModel

•\

Implemented the INotifyPropertyChanged interface

•\

Added a property that when set will check whether

 

it’s value really has changed, and if it has, raise the

 

PropertyChanged event with the name of the property

 

that has changed

•\

Added a method to set the Time property and repeat

 

every second so that the widget looks like a clock

 

counting.

82