C#C
C#4mo ago
BigBallard

✅ Creating ViewModel for Maui doesn't propagate changes

I am attempting to cleanup my Maui app a bit and wanted to create an abstract class ViewModel that implements the boilerplate code for INotifyPropertyChanged.

When I user ViewModel on an already functioning page, the properties are not being updated and displayed to the bound control.

ViewModel
public abstract class ViewModel: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected bool SetField<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }
}

SignUpViewModel
using System.ComponentModel;
using System.Net.Mail;
using System.Runtime.CompilerServices;
using System.Windows.Input;

namespace ToolerMobile.Pages;

public class SignUpViewModel : ViewModel
{
    private string _email = "", _errorMessage = "";

    public string Email
    {
        get => _email;
        set
        {
            _email = value;
            ValidateForm();
        }
    }

    public string ErrorMessage
    {
        get => _errorMessage;
        private set
        {
            _errorMessage = value;
            SetField(ref _errorMessage, value);
        }
    }

    private void ValidateForm()
    {
        ErrorMessage = "";
        try
        {
            if (_email.Length == 0)
            {
                return;
            }
            new MailAddress(_email);
        }
        catch (Exception e)
        {
            ErrorMessage = "Invalid email address.";
        }
}


With this, ErrorMessage changes are not shown in the app where if I implment INotifyPropertyChanged directly, it works.
Was this page helpful?