Is it possible to use "PropertyChanged" on a bool in .NET MAUI?

1.8k Views Asked by At

I have been trying to detect it when these variables change, but I don't know how to do that since bools aren't supported by the "PropertyChanged" function. I also tried using the communityToolKit, but I have no idea how to use that. I want it to call the function "IconUpdater"

public class Status : INotifyPropertyChanged
{
    
    public static bool isWorking { get; set; } = Preferences.Get("IsWorking", true);
    public static bool isPaused { get; set; } = Preferences.Get("IsPaused", false);


    public static void IconUpdater()
    {
       // The function I want to call \\
    }
    public event PropertyChangedEventHandler PropertyChanged;
}
2

There are 2 best solutions below

0
Alexandar May - MSFT On BEST ANSWER

You can use PropertyChanged event to notify the changes of IsEnabled property in your viewmodel. Here's the code snippet below for your reference:


    public class MainPageViewModel : INotifyPropertyChanged 
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private bool _isWorking;

        public bool IsEnabled
        {
            get
            {
                return _isWorking;
            }


            set
            {
                if(_isWorking != value)
                {
                    _isWorking = value;
                    var args = new PropertyChangedEventArgs(nameof(IsEnabled));
                    PropertyChanged?.Invoke(this, args);
                }
            }
        }

    
    }

0
Julian On

I recommend using the Community Toolkit MVVM package: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/

You can then simply do the following to use the INotifyPropertyChanged interface:

using CommunityToolkit.Mvvm;

public class MyViewModel : ObservableObject
{
    private bool _myBool;
    public bool MyBool
    {
        get => _myBool;
        set => SetProperty(ref _myBool, value); 
    }
}

You can also modify the code in such a way that you directly call any other method from within the setter:

private bool _myBool;
public bool MyBool
{
    get => _myBool;
    set
    {
        SetProperty(ref _myBool, value); 
        IconUpdater();
    }
}

Please mind that your class is using static properties. You cannot use INotifyPropertyChanged for that.