INotifyPropertyChanged:通知另一个类 [英] INotifyPropertyChanged: Notify another class
问题描述
我有一个类(让我们称之为 MyContainerClass
),它是几个其他类的容器(我们称之为 ClassA
到 ClassF
)。 ClassA
to ClassF
继承相同的基类(让我们称之为 MyBaseClass
)。在 MyBaseClass
我有一个int属性,名称为 Count
,其中 ClassA
到 ClassF
继承。我还有一个在 MyContainerClass
中具有相同名称的int属性,它是 ClassA
到 ClassF
。
I have a class (let's call it MyContainerClass
)that is a container for several other classes (let's call them ClassA
to ClassF
). ClassA
to ClassF
inherit the same base class (let's call it MyBaseClass
). In MyBaseClass
I have an int property with the name Count
, which ClassA
to ClassF
inherit. I also have an int property with the same name in MyContainerClass
which is the sum of ClassA
to ClassF
.
然后我有一个datagrid,每行都有一个对象 MyContainerClass
。网格的列显示 ClassA
至 ClassF
。网格中的最后一列显示一个总计(即它被绑定到 MyContainerClass
的 Count
属性。现在我希望在A-F范围内的任何类中更改 Count
属性时,最后一列中的总计更新。我在 MyBaseClass
中实现了INotifyPropertyChanged,当我在 ClassA c>中更改
Count
/ code>到 ClassF
。但是我的datagrid中的最后一列保持不变。任何线索?
Then I have a datagrid, and each row has one object of MyContainerClass
. The columns of the grid show ClassA
to ClassF
. The last column in the grid shows a total (that is it is bound the Count
property of MyContainerClass
). Now I want that the total in the last column updates as soon as I change the Count
property in any class in the A-F range. I implemented INotifyPropertyChanged in MyBaseClass
and it does fire when I change the Count
property in ClassA
to ClassF
. But the last column in my datagrid remains the same. Any clues?
编辑:
我创建了一个类图。
I have created a class diagram.
getCount()方法返回objA.Count + objB.Count + ... + objF.Count,并由 MyContainerClass
Count 属性返回>。问题是:如果我更新objA.Count我想要GUI(即我的datagrid中的列)显示更新的和。
The getCount() method returns objA.Count+objB.Count+...+objF.Count and is returned by the Count
property in the MyContainerClass
. The question is: if I update objA.Count I want the GUI (that is the column in my datagrid) to display the updated sum.
推荐答案
只需实现 INotifyPropertyChanged
不足以进行自动更新。 MyContainerClass
对象需要订阅其他列中的 MyBaseClass
对象的更改通知。您可以通过将以下方法添加到 MyContainerClass
中:
Just implementing INotifyPropertyChanged
is not enough for an automatic update. The MyContainerClass
object needs to "subscribe" to the change notifications of the MyBaseClass
objects in the other columns. One way you can handle this is by adding a method like the following to the MyContainerClass
:
void SubscribeToCount(MyBaseClass item)
{
item.PropertyChanged += (s,e) =>
this.Sum += (e.NewValue - e.OldValue);
}
您可以为其他列中的所有对象调用此方法。 (这个问题不清楚,但是我假设有一个包装类,其中包含 MyClassA-F
和 MyContainerClass
,它将数据网格绑定到这个包装器类的集合)。
And you call this method for all the objects in the other columns. (It's not clear from the question but I assume there is a wrapper class that includes instances of MyClassA-F
and MyContainerClass
, which you bind the datagrid to a collection of this wrapper class).
这篇关于INotifyPropertyChanged:通知另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!