为嵌套属性实现 INotifyPropertyChanged [英] Implementing INotifyPropertyChanged for nested properties
问题描述
我有一个 Person 类:
I have a Person class:
public class Person : INotifyPropertyChanged
{
private string _name;
public string Name{
get { return _name; }
set {
if ( _name != value ) {
_name = value;
OnPropertyChanged( "Name" );
}
}
private Address _primaryAddress;
public Address PrimaryAddress {
get { return _primaryAddress; }
set {
if ( _primaryAddress != value ) {
_primaryAddress = value;
OnPropertyChanged( "PrimaryAddress" );
}
}
//OnPropertyChanged code goes here
}
我有一个地址类:
public class Address : INotifyPropertyChanged
{
private string _streetone;
public string StreetOne{
get { return _streetone; }
set {
if ( _streetone != value ) {
_streetone = value;
OnPropertyChanged( "StreetOne" );
}
}
//Other fields here
//OnPropertyChanged code goes here
}
我有一个视图模型:
public class MyViewModel
{
//constructor and other stuff here
private Person _person;
public Person Person{
get { return _person; }
set {
if ( _person != value ) {
_person = value;
OnPropertyChanged( "Person" );
}
}
}
我有一个视图,其中包含以下几行:
I have a View which has the following lines:
<TextBox Text="{Binding Person.Name, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged />
<TextBox Text="{Binding Person.Address.StreetOne, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged />
当视图加载时,两个值都显示在文本框中.
Both values show up in the text box ok when the view loads.
对第一个文本框的更改将触发 MyViewModel 中的 OnPropertyChanged( "Person" )
.太好了.
Changes to the first text box will fire OnPropertyChanged( "Person" )
in MyViewModel. Great.
对第二个文本框("Person.Address.StreetOne")
的更改不会在MyViewModel 内触发OnPropertyChanged("Person")
.这意味着它不会调用 Person 对象的 SET 方法.不是很好.有趣的是,调用了 Address 类中 StreetOne 的 SET 方法.
Changes to the second text box ("Person.Address.StreetOne")
does NOT fire OnPropertyChanged( "Person" )
inside MyViewModel. Meaning it doesn't call the Person object's SET method. Not great. Interestingly the SET method of StreetOne inside the Address class is called.
当Person.Address.StreetOne
发生变化时,如何获取ViewModel内部Person对象的SET方法被调用???
How do I get the SET method of the Person object inside the ViewModel to be called when Person.Address.StreetOne
is changed???
我是否需要扁平化我的数据,以便 SteetOne 在 Person 而不是 Address 中?
Do I need to flatten my data so SteetOne is inside Person and not Address??
谢谢!
推荐答案
如果你想调用 viewmodel SET 你可以创建一个 street 属性
if you want the viewmodel SET to be called you could create a street property
public class MyViewModel
{
//constructor and other stuff here
public string Street{
get { return this.Person.PrimaryAddress.StreetOne; }
set {
if ( this.Person.PrimaryAddress.StreetOne!= value ) {
this.Person.PrimaryAddress.StreetOne = value;
OnPropertyChanged( "Street" );
}
}
}
xml
<TextBox Text="{Binding Street, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged />
但是这个解决方案有它的缺点.我在我的项目中使用 Reeds 的答案
but this solution has its drawbacks. i go with Reeds answer in my projects
这篇关于为嵌套属性实现 INotifyPropertyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!