3

我正在使用 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

4

2 回答 2

2

您可以使用接口的PropertyChanged事件INotifyPropertyChanged告诉您子属性何时发生变化。

在你的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);
}
于 2014-08-12T15:41:54.303 回答
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 事件

于 2014-08-12T15:44:23.183 回答