MVVM如何在嵌套对象属性更新时得到通知? [英] MVVM How to get notified when nested objects properties are updated?
本文介绍了MVVM如何在嵌套对象属性更新时得到通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如
class child : ObservableObject{
private int _prop;
public int prop{
get {
return _prop;
}
set {
_prop=value;
OnPropertyChanged("prop");
}
}
class parent : ObservableObject{
private child _mychild;
public child mychild{
get {
return _mychild;
}
set {
_mychild=value;
OnPropertyChanged("mychild");
OnPropertyChanged("pow");
}
}
public int pow{
return _mychild.prop*2;
}
}
parent myobj;
myobj.child.prop=1;
如何获得有关bar.z更新的通知?我已经绑定了嵌套属性并更新了视图,但是绑定了bar.pow的部分没有得到更新.
How do I get notified that bar.z is updated? I have binded the nested property and updates the view, but the part where bar.pow is binded does not get updated.
<Textbox Text={Binding myobj.child.prop}/>
<Textbox Text={Binding myobj.pow}/>
即时通讯试图在更新第一个文本框时更新第二个文本框.
What im trying to do is update the second textbox when the first textbox is updated.
推荐答案
您必须在父对象中预订子对象的PropertyChanged
,并在事件处理程序中向视图通知child.PropertyChanged
哪些属性受到了影响.不要忘记取消订阅先前的对象.
You have to subscribe in parent object to the PropertyChanged
of a child object and notify view in event handler for child.PropertyChanged
which properties are impacted. Don't forget to unsubscribe by previous object.
class foo: ObservableObject
{
private int _x;
public int x
{
get
{
return _x;
}
set
{
_x = value;
OnPropertyChanged("x");
}
}
class bar : ObservableObject
{
private foo _y;
public foo y
{
get
{
return _y;
}
set
{
if (_y!=null)
{
_y.PropertyChanged -= _y_PropertyChanged;
}
_y = value;
_y.PropertyChanged += _y_PropertyChanged;
OnPropertyChanged("y");
OnPropertyChanged("pow");
}
}
private void _y_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
//if(e.PropertyName == "x");
//{
OnPropertyChanged("pow");
OnPropertyChanged("y");
//}
}
public int pow { get { return _y.x * 2;} }
}
这篇关于MVVM如何在嵌套对象属性更新时得到通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文