我创建了两个viewmodel,MyViewModel,MyViewModel2。 MyViewModel2包含MyViewModel作为属性。 MyViewModel包含来自EF / WCF Ria服务的一个实体MyEntity。
在MyViewModel2中,我想捕获MyEntity中的任何项目更改以进行数据绑定。我的代码如下:
public class MyViewModel : ViewModelBase
{
//....
public MyViewModel(myEntity myEntity)
: this()
{
//....
this._myEntity = myEntity;
this._myEntity.PropertyChanged += new PropertyChangedEventHandler(_myEntity_PropertyChanged);
this.RaisePropertyChanged("MyEntity");
}
void _myEntity_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
this.RaisePropertyChanged("MyEntity");
}
private MyEntity _myEntity;
public MyEntity MyEntity
{
get { return this._myEntity; }
set
{
if (value != this._myEntity)
{
this._myEntity = value;
RaisePropertyChanged("MyEntity");
}
}
}
}
public class MyViewModel2 : ViewModelBase
{
public MyViewModel2(){
this._MyViewModel = new MyViewModel();
this._MyViewModel.PropertyChanged += new PropertyChangedEventHandler(_MyViewModel_PropertyChanged);
}
void _MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
//do something here....
}
private MyViewModel _MyViewModel;
public MyViewModel MyViewModel
{
get { return this._MyViewModel; }
set
{
if (value != this._MyViewModel)
{
this._MyViewModel = value;
RaisePropertyChanged("MyViewModel");
}
}
}
}
然后我运行应用程序并更改MyEntity中的数据,但我无法在MyViewModel2中捕获已更改的事件。
如何解决此问题?
答案 0 :(得分:0)
您是否正在更改myViewModel._myEntity或myViewModel._myEntity.SomeProperty的值?
在您提供的代码中,MyViewModel仅在字段'_myEntity'值更改时引发PropertyChanged事件,而不是更改值'on''_ myEntity'实例。
要在_myEntity上正确引发PropertyChange通知,您应该在MyEntity的属性设置器下添加PropertyChanged事件调用代码,例如:
public class MyEntity
{
private string _name;
public string Name
{
get
{
return this._name;
}
set
{
if(value != this._name)
{
this._name = vaule;
this.RaisePropertyChanged("Name");
}
}
}