Updating a property based on a model with MVVM.CommunityToolkit in WPF

243 Views Asked by At

I'm building a new application, and I'm using the MVVM.CommunityToolkit for the first time. When using ObservableObject on my viewmodel and ObservableProperty attributes on the property I am getting some strange behavior with the INotifyPropertyChanged implementation.

First of all - this is my code for the property in question:

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(ValidateLoginCommand))]
[NotifyCanExecuteChangedFor(nameof(AddMasterCommand))]
private Master _master;

And this is the model used in the property:

public class Master : BaseAccount
{
    //Linking
    public virtual ICollection<Slave> Slaves { get; set; }

}

Which inherits the BaseAccount:

public partial class BaseAccount : ObservableObject
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty; //
    public string Comment { get; set; } = string.Empty; //
    public bool Connected { get; set; } = false; 
    public string AccountName { get; set; } = string.Empty;//
    public string AccountPassword { get; set; } //
    public double Profit { get; set; } = 0;
    public double DrawDown { get; set; } = 0;
    public double DrawDownPercentage { get; set; } = 0;
    public string? Token { get; set; }
    public bool IsMT5 { get; set; }
    public virtual AccountSummary AccountSummary { get; set; } = new AccountSummary();
    public virtual Broker Broker { get; set; } = new Broker(); //


    //Grouping
    public string GroupName { get; set; } = string.Empty;

    //CopySettings
    public bool CopyByEquity { get; set; }
    public double LotRatio { get; set; } = 1.000;
    public double MinLot { get; set; } = 0.00;
    public double MaxLot { get; set; } = 0.00;
}

The issue is that whenever i change the Master properties e.g. Master.Name the propertychanged behaviors like [NotifyCanExecuteChangedFor] attribute or OnMasterChanged event is not triggering.

I'm doing this in a WPF application

Is this expected behavior, or what am I doing wrong? I tried playing around and reading about the ObservableObject, ObservableProperty and combing through the documentation of ObservableProperty but without any luck of getting this to work.

I've factored my code to having individual properties for each Master property and then assigning them to the Master but this is not a good solution and clutters every function and viewmodel for me, so I would love a solution for this.

1

There are 1 best solutions below

0
On

The OnMasterChanged is only invoked in case you reassign the Master property. It itself does not know when properties of the object are changed.

It seems you want to get notified when the properties change. In order to do that you need to make these properties observable, not the container. In particular you should specify the observable properties inside the BaseAccount class.