MVVM层次结构中的更改通知 [英] Change Notification in MVVM Hierarchies
问题描述
让我们在一些抽象的ViewModel基类中说,我有一个普通的属性,如下所示:
Let's say in some abstract ViewModel base-class I have a plain-old property as follows:
public Size Size
{
get { return _size; }
set
{
_size = value;
OnPropertyChanged("Size");
}
}
然后我创建一个更具体的ViewModel,继承自上一个ViewModel,该模型包含以下属性:
I then create a more specific ViewModel, inheriting from the previous one, which contains the following property:
public Rect Rectangle
{
get { return new Rect(0, 0, _size.Width, _size.Height); }
}
现在,在某些View类中,我绑定到上述ViewModel的Rectangle
属性.一切正常,直到我更改大小.当Size
更改时,Rectangle
对此一无所知,并且更改不会传播到视图.而且由于Rectangle
在子类中,所以我不能简单地将OnPropertyChanged("Rectangle")
添加到Size
设置器中.
Now, in some View class I bind to the aforementioned ViewModel's Rectangle
property. Everything works fine, until I change the size. When Size
changes, Rectangle
doesn't know about it and the change doesn't propagate to the View. And since Rectangle
is in the child class, I can't simply add an OnPropertyChanged("Rectangle")
to the Size
setter.
现在想象一下,我有许多不同的属性,例如Rectangle
,它们都依赖于基类属性,并且这些更改都没有被传播.我需要一种轻巧而优雅的方式来链接变更通知,最好是不需要大量代码并且不会强迫我使用依赖项属性的方式.
Now imagine that I have many different properties like Rectangle
, that all depend on base-class properties, and that none of these changes are being propagated. I need some lightweight and elegant way of chaining change notifications, preferably one that doesn't require a lot of code and doesn't force me into using dependency properties.
显然,这里有很多丑陋的解决方案-我正在寻找的是干净,聪明的东西.在我看来,这将是一个非常常见的情况,并且在我看来,这可能是一种 MVVM友好的方式.
Obviously there are a lot of ugly solutions here- what I am looking for is something clean and clever. It seems to me this would be a very common scenario, and it seems to me there might be an MVVM-friendly way of doing this.
推荐答案
我最近在博客中谈到了这个确切的问题.我在矩形中包含一个[DependsUpon("Size")]
属性.我真的很喜欢这种方法,因为它通过创建依赖项的代码保留了依赖项知识,而不是相反.
I recently blogged about this exact problem. I include a [DependsUpon("Size")]
attribute with the Rectangle. I REALLY like this approach, because it keeps the dependency knowledge with the code that creates the dependency, not the other way around.
看看: 查看全文