Search code examples
c#viewmodelmvpinotifypropertychanged

Invoking PropertyChanged from a Method to update properties


I am trying to figure out how to update my bool properties inside a ViewModel using INotifyPropertyChanged?

Basically in my ViewModel I pass in a List of string. Each boolean properties check the list to see if a string value exists.

Now in my software lifecycle the list will get updated and inturn I would like to update each properties using INotifyPropertyChanged.

My question is how do I invoke the INotifyPropertyChanged from a AddToList method? Is using a method for this the correct direction?

public class ViewModel : INotifyPropertyChanged
{   
    private List<string> _listOfStrings;

    public ViewModel(List<string> ListOfStrings)
    {   
        _listOfStrings = ListOfStrings;     
    }

    public bool EnableProperty1 => _listOfStrings.Any(x => x == "Test1");
    public bool EnableProperty2 => _listOfStrings.Any(x => x == "Test2");
    public bool EnableProperty3 => _listOfStrings.Any(x => x == "Test3");
    public bool EnableProperty4 => _listOfStrings.Any(x => x == "Test4");

    public void AddToList(string value)
    {
        _listOfStrings.Add(financialProductType);
        // Should I call the OnPropertyChanged here     
    }

    public event PropertyChangedEventHandler PropertyChanged;

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

Solution

  • The easiest thing to do here would be to manually call OnPropertyChanged in the AddString method.

    public void AddToList(string value)
    {
        _listOfStrings.Add(financialProductType);
        OnPropertyChanged("EnableProperty1");
        OnPropertyChanged("EnableProperty2");
        // etc
    }
    

    This is fine if you're not likely to change the class much. If you add another property that's calculated from _listOfStrings you'll need to add a OnPropertyChanged call here.

    Using an ObservableCollection doesn't really help because you already know when the list changes (AddToList) and you'll still have to trigger all the OnPropertyChanged methods anyway.