Model widoku i komenda

Wiązanie danych i MVVM: BindingContext, Binding i Command - Aplikacje mobilne: .NET MAUI krok po kroku (maui)

Klasa MainViewModel trzyma licznik. Setter Count woła OnPropertyChanged(), a zdarzenie PropertyChanged mówi etykiecie {Binding Count}, że ma się odświeżyć. Konstruktor strony ustawia BindingContext = new MainViewModel(), a przycisk wykonuje IncrementCommand (klasa Command z metodą do wykonania). Strona nie ma żadnej metody Clicked.

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"
             x:Class="MauiApp1.MainPage"
             Title="Licznik">
    <VerticalStackLayout Padding="20" Spacing="15">
        <Label x:Name="CountLabel" Text="{Binding Count}" FontSize="48" HorizontalOptions="Center"/>
        <Button x:Name="PlusBtn" Text="+1" Command="{Binding IncrementCommand}"/>
        <Button x:Name="ResetBtn" Text="Zeruj" Command="{Binding ResetCommand}"/>
    </VerticalStackLayout>
</ContentPage>

MainPage.xaml.cs

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace MauiApp1
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private int count;

        public int Count
        {
            get => count;
            set { count = value; OnPropertyChanged(); }
        }

        public Command IncrementCommand { get; }
        public Command ResetCommand { get; }

        public MainViewModel()
        {
            IncrementCommand = new Command(() => Count++);
            ResetCommand = new Command(() => Count = 0);
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged([CallerMemberName] string name = null) =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            BindingContext = new MainViewModel();
        }
    }
}

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu Aplikacje mobilne: .NET MAUI krok po kroku·Zaloguj się, aby zapisać postęp na koncie.