我正在使用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
触发?
答案 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.
}
请参阅此处的文档