【发布时间】:2018-09-06 20:10:23
【问题描述】:
我想建立一个可以从中派生的类。该类应建立一个逻辑,以便它从 Property 中传输 propertychanged 事件,而 Property 本身就是具有 Property 的类。
所以请查看代码。目标是当我将 catList[0].MyPerson.Name = "Peter"; 更改为 Peter 时,从 BindingList 中抛出 ListChanged 事件。
我的问题是,当我在 NestedPropertyHolder 中时,我不知道如何获得实现 NestedPropertyHolder 的类。换句话说,我是如何得到我的继承人的......希望你明白我想要做什么。
static void Main(string[] args)
{
BindingList<Category> catList = new BindingList<Category>();
catList.ListChanged += CatList_ListChanged;
Category cat = new Category();
Person pers = new Person();
pers.Name = "Rene";
cat.MyPerson = pers;
catList.Add(cat);
catList[0].MyPerson.Name = "Peter";
}
public class NestedPropertyHolder
{
public NestedPropertyHolder()
{
//List of Propertys of the class that is deriving from NestedPropertyHolder -> Should have "MyPerson" from Category
List<object> listOfPropertysImplementingINotifyPropertyChanged = new List<object>();
for(int i = 0; i < listOfPropertysImplementingINotifyPropertyChanged.Count; i++)
{
if(listOfPropertysImplementingINotifyPropertyChanged[i] is INotifyPropertyChanged)
{
(listOfPropertysImplementingINotifyPropertyChanged[i] as INotifyPropertyChanged).PropertyChanged += NestedPropertyHolder_PropertyChanged;
}
}
}
private void NestedPropertyHolder_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
//That class that is deriving from NestedPropertyHolder -> should be "Category"
object classThatDerivedFromThisClass = new object();
//classThatDerivedFromThisClass.PropertyChanged(sender, e.PropertyName);
}
}
}
public class Category : NestedPropertyHolder, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
Person myPerson = new Person();
public Person MyPerson
{
get
{
return myPerson;
}
set
{
myPerson = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("MyPerson"));
}
}
}
public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
}
感谢您的帮助:)
更新:发现一个关于同一主题的有趣线程 When nesting properties that implement INotifyPropertyChanged must the parent object propogate changes?
【问题讨论】:
-
"目标是在我更改时从 BindingList 中抛出 ListChanged 事件" 不,不要那样做。如果您想观察集合中项目的变化,请将观察者连接到单个项目的通知。不要!尝试聚合父级中的更改。
-
你是什么意思“挂钩观察者到个别项目的通知”?什么是观察者?你有任何样品吗? ^^
-
观察者是订阅事件的代码。
-
如果我理解你的话,你希望我直接订阅属性的更改事件,而不是被列表事件注意到吗?为什么不 ?我觉得这很优雅?因为如果列表的任何内部元素发生变化,我必须重新绘制列表。
标签: c# nested inotifypropertychanged bindinglist propertychanged