MVVM Detect property change of subclass

2.3k views Asked by At

I am using SimpleMVVM and have two separate classes (models), one using the second like this:

    public class Database : ModelBase<Database>
    {
        public String ServerName //{ get; set; }
        {
            get { return _ServerName; }
            set
            {
                if (_ServerName != value)
                {
                    _ServerName = value;
                    NotifyPropertyChanged(m => m.ServerName);
                }
            }
        }
        private String _ServerName = "MyTestServer";

        // other properties removed for brevity
    }

public class MyConfiguration
{
        /// <summary>
        /// Database information
        /// </summary>
        public Database DatabaseInfo
        {
            get { return _DatabaseInfo; }
            set
            {
                if (_DatabaseInfo != value)
                {
                    _DatabaseInfo = value;
                    NotifyPropertyChanged(m => m.DatabaseInfo);
                }
            }

        }
        private Database _DatabaseInfo = new Database();
}

When 'ServerName' is changed, the NotifyPropertyChanged(m => m.ServerName); command executes but NOT NotifyPropertyChanged(m => m.DatabaseInfo);

How do I make the NotifyPropertyChanged(m => m.DatabaseInfo); fire whenever one of the properties of Database changes?

2

There are 2 answers

2
Sheridan On

You can use the PropertyChanged event of the INotifyPropertyChanged interface to tell you when the child property changes.

In your MyConfiguration class:

public Database DatabaseInfo
{
    get { return _DatabaseInfo; }
    set
    {
        if (_DatabaseInfo != value)
        {
            _DatabaseInfo = value;
            NotifyPropertyChanged(m => m.DatabaseInfo);
            DatabaseInfo.PropertyChanged += DataBasePropertyChanged;
        }
    }
}

...

private void DataBasePropertyChanged(object sender, PropertyChangedEventArgs e)
{
    NotifyPropertyChanged(m => m.DatabaseInfo);
}

Please note that you will need to attach this listener each time that you change the DatabaseInfo property value. Also, note that if you just wanted to listen to one property, then you could have done this:

private void DataBasePropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "ServerName") NotifyPropertyChanged(m => m.DatabaseInfo);
}
0
Jon On
private Database _DatabaseInfo = new Database();

public MyConfiguration()
{
  this._DatabaseInfo.PropertyChanged += new PropertyChangedEventHandler(propChanged);
}

private void propChanged(object sender, PropertyChangedEventArgs e)
{
  // Now you can update the _DatabaseInfo.DatabaseInfo property to force the property changed event to fire.
}

Refer to the documentation here

INotifyPropertyChanged.PropertyChanged event