2

If I add something to my collection, the UI is updated, so my bindings are in order. If I make an update to the collection, the UI is not updated until I navigate away from the page and back to it.

My collection definition:

public ObservableCollection<Account> Accounts = new();

Account definition:

public class Account
{
    public int Id { get; set; }
    public string AccountName { get; set; }
    public decimal StartingBalance { get; set; }

    public override string ToString()
    {
        return $"Id: {Id}: {AccountName} | {StartingBalance}";

    }
}

I make updates like this:

public void EditAccount(string editAccountName, string editAccountStartingBalance, int editAccountId)
{
    decimal startingBalance;
    Decimal.TryParse(editAccountStartingBalance, out startingBalance);
    Account editAccount = Accounts.FirstOrDefault(x => x.Id == editAccountId);
    editAccount.AccountName = editAccountName;
    editAccount.StartingBalance = startingBalance;
}

As I typed up my question, I found through other questions that I need to do the following:

private ObservableCollection<Account> _accounts = new();
public ObservableCollection<Account> Accounts
{
    get { return _accounts; }
    set
    {
        _accounts = value;
        RaisePropertyChanged("Accounts");
    }
}
                        
public event PropertyChangedEventHandler PropertyChanged;

private void RaisePropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if(handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

This isn't updating the UI either. I can see via stepping through the code that the collection itself is updated, but it's still not reflected in the UI until I navigate away from the page then back.

Code snippets have been pared down for brevity. I think I included all the needed deets. :) With so many things automagically working in .NET MAUI, I think I'm expecting too much, lol.

XJonOneX
  • 305
  • 2
  • 11
  • 1
    there are hundreds of existing questions on this same problem that will all tell you your class needs to implement `INotifyPropertyChanged` – Jason Nov 04 '22 at 00:59
  • 1
    if you want the UI to update when a property on `Account` is updated, then`Account` needs to implement `INotifyPropertyChanged` (or inherit `ObservableObject`) – Jason Nov 04 '22 at 01:26

1 Answers1

1

So I'm using the CommunityToolkit.MVVM package, and just needed to set [ObservableProperty] on my Account type fields and have it inherit ObservableObject.

public partial class Account : ObservableObject
{
    [ObservableProperty]
    public int id;
    [ObservableProperty]
    public string accountName;
    [ObservableProperty]
    public decimal startingBalance;

    public override string ToString()
    {
        return $"Id: {Id}: {AccountName} | {StartingBalance}";

    }
}
XJonOneX
  • 305
  • 2
  • 11