Pole w obie strony i CanExecute

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

Entry z Text="{Binding Name}" działa w obie strony: wpisany tekst trafia do właściwości Name. Setter Name zgłasza też zmianę Greeting i woła SaveCommand.ChangeCanExecute(). Drugi argument Command (CanExecute) mówi, kiedy przycisk jest aktywny: tu tylko z wpisanym imieniem.

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="Profil">
    <VerticalStackLayout Padding="20" Spacing="15">
        <Entry Placeholder="Imię" Text="{Binding Name}"/>
        <Label Text="{Binding Greeting}" FontSize="22"/>
        <Button Text="Zapisz" Command="{Binding SaveCommand}"/>
        <Label Text="{Binding Saved}" TextColor="Green"/>
    </VerticalStackLayout>
</ContentPage>

MainPage.xaml.cs

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

namespace MauiApp1
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private string name = "";
        private string saved = "";

        public string Name
        {
            get => name;
            set
            {
                name = value ?? "";
                OnPropertyChanged();
                OnPropertyChanged(nameof(Greeting));
                SaveCommand.ChangeCanExecute();
            }
        }

        public string Greeting => name.Length > 0 ? $"Cześć, {name}!" : "Podaj imię";

        public string Saved
        {
            get => saved;
            set { saved = value; OnPropertyChanged(); }
        }

        public Command SaveCommand { get; }

        public MainViewModel()
        {
            SaveCommand = new Command(() => Saved = $"Zapisano: {name}", () => name.Length > 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.