ClockViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Lab1_2_MAUI_XAML
{
public class ClockViewModel : INotifyPropertyChanged
{
DateTime _dateTime;
Timer _timer;
public event PropertyChangedEventHandler PropertyChanged;
public DateTime DateTime
{
get => _dateTime;
set
{
{
if (_dateTime != value)
_dateTime = value;
OnPropertyChanged();
}
}
}
public ClockViewModel()
{
this.DateTime = DateTime.Now;
_timer = new Timer(new TimerCallback((s) =>
this.DateTime = DateTime.Now),
null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
}
~ClockViewModel() => _timer.Dispose();
public void OnPropertyChanged([CallerMemberName]
string name = "") => PropertyChanged?.Invoke(this,
new PropertyChangedEventArgs(name));
}
}
MainPage.xaml.cs
namespace Lab1_2_MAUI_XAML
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
}
}
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Lab1_2_MAUI_XAML;
assembly=Lab1_2_MAUI_XAML"
x:Class="Lab1_2_MAUI_XAML.MainPage"
Title="Clock Page"
x:DataType="local:ClockViewModel"
BackgroundColor="Aqua">
<ContentPage.BindingContext>
<local:ClockViewModel />
</ContentPage.BindingContext>
<Label Text= "{Binding DateTime, StringFormat='{0:T}'}"
FontSize="60"
TextColor="Black"
BackgroundColor="Orange"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
FontAttributes="Bold"
HorizontalOptions="Center"
VerticalOptions="Center" />
</ContentPage>