当绑定到 getter 属性 时,如何让 INotifyPropertyChanged 绑定更改?
How to get INotifyPropertyChanged binding to change when it is bound to a getter property?
我有一个这样的虚拟机
class Vm : Notifiable
{
public string Name
{
get { return _Name; }
set { _Name = value; OnPropertyChanged("Name"); }
}
private _Name = "";
}
还有一个像这样
class CollectionVm : Notifiable
{
public ObservableCollection<Vm> Vms {get;set;}
public Vm Selected
{
get { return _Selected; }
set { _Selected= value; OnPropertyChanged("Selected"); }
}
Vm _Selected = null;
}
第三个像这样
class OuterVm : Notifiable
{
CollectionVm _collection;
public Vm Display
{
get {return _collection.Selected; }
}
}
还有像这样的绑定
<TextBlock Text={Binding Display.Name}/>
我的问题是,当集合中的选择发生变化时,文本块不会更新。我怎样才能做到这一点?
这需要一种机制来引发 OuterVm
中的 PropertyChanged
事件。
一个简单的选择是订阅事件并通过它们传递:
class OuterVm : Notifiable
{
public OuterVm()
{
// initialize _collection
_collection.PropertyChanged += (o,e) =>
{
if (e.PropertyName == "Selected")
OnPropertyChanged("Display");
};
}
CollectionVm _collection;
public Vm Display
{
get {return _collection.Selected; }
}
}
我有一个这样的虚拟机
class Vm : Notifiable
{
public string Name
{
get { return _Name; }
set { _Name = value; OnPropertyChanged("Name"); }
}
private _Name = "";
}
还有一个像这样
class CollectionVm : Notifiable
{
public ObservableCollection<Vm> Vms {get;set;}
public Vm Selected
{
get { return _Selected; }
set { _Selected= value; OnPropertyChanged("Selected"); }
}
Vm _Selected = null;
}
第三个像这样
class OuterVm : Notifiable
{
CollectionVm _collection;
public Vm Display
{
get {return _collection.Selected; }
}
}
还有像这样的绑定
<TextBlock Text={Binding Display.Name}/>
我的问题是,当集合中的选择发生变化时,文本块不会更新。我怎样才能做到这一点?
这需要一种机制来引发 OuterVm
中的 PropertyChanged
事件。
一个简单的选择是订阅事件并通过它们传递:
class OuterVm : Notifiable
{
public OuterVm()
{
// initialize _collection
_collection.PropertyChanged += (o,e) =>
{
if (e.PropertyName == "Selected")
OnPropertyChanged("Display");
};
}
CollectionVm _collection;
public Vm Display
{
get {return _collection.Selected; }
}
}