MVVM检测子类的属性更改

时间:2014-08-12 15:31:48

标签: c# wpf mvvm inotifypropertychanged simple-mvvm

我正在使用SimpleMVVM并且有两个单独的类(模型),一个使用第二个类:

    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();
}

更改'ServerName'后,NotifyPropertyChanged(m => m.ServerName);命令会执行,但不会NotifyPropertyChanged(m => m.DatabaseInfo);

如果NotifyPropertyChanged(m => m.DatabaseInfo);的某个属性发生变化,如何使Database触发?

2 个答案:

答案 0 :(得分:2)

您可以使用INotifyPropertyChanged界面的PropertyChanged event告诉您子属性更改的时间。

MyConfiguration课程中:

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);
}

请注意,每次更改DatabaseInfo属性值时,都需要附加此侦听器。另外,请注意,如果您只想听一个属性,那么您可以这样做:

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

答案 1 :(得分:0)

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.
}

请参阅此处的文档

INotifyPropertyChanged.PropertyChanged event