我正在使用" Simple MVVM Toolkit" (MVVM
noob here)开发一个C#WPF应用程序。
我有一个名为A
的模型类:
public class A : ModelBase<A>
{
//properties, constructors, methods..
}
..和另一个名为B
的模型类,它继承自A
但公开了A
没有的属性:
public class B : A
{
private string additionalProperty;
public string AdditionalProperty
{
get { return additionalProperty; }
set
{
additionalProperty = value;
//NotifyPropertyChanged(m => m.AdditionalProperty); <-- problem here
}
}
}
上面的注释行出现问题:NotifyPropertyChanged
中的lambda因为m.AdditionalProperty
不存在而无法工作,因为m
的类型为{{1} },而不是A
。在这种情况下会发生什么?我应该注意B
附带工具包,而不是自定义实现。
编辑:以下是NotifyPropertyChanged
中NotifyPropertyChanged
的智能感知说明:
B
允许您为通知属性更改指定lambda
答案 0 :(得分:2)
问题在于他们如何实施ModelBase
。他们显然没有觉得有人会将ModelBase
的子类化为子类,我不确定他们为什么这么认为。
在任何情况下,问题在于,当您指定通用名称ModelBase
时,您会告诉ModelBase<A>
使用什么类型来解决问题。为了解决这个问题,你必须做一些相当复杂的通用游戏,看起来很傻:
public class A<T> : ModelBase<T> where T : A<T>
{
//properties, constructors, methods..
}
public class B : A<B>
{
private string additionalProperty;
public string AdditionalProperty
{
get { return additionalProperty; }
set
{
additionalProperty = value;
NotifyPropertyChanged(m => m.AdditionalProperty);
}
}
}
请注意,A
现在继承自ModelBase<T>
而不是ModelBase<A>
,并且您将T
限制为A<T>
。然后,您B
继承A
并将其通用指定为B
(实现A<T>
)。
这是相当复杂的,我不确定他们为什么这样做 - 可能是因为有一些跨平台的事情要求他们这样做。如果你不需要这个用于跨平台工作,或者他们可能因为这个原因没有这样做,我建议你使用类似MVVM Light的东西来满足你的MVVM需求。它具有不同的NotifyPropertyChanged
实现,它不依赖于指定自己的类型,并且减少了对泛型的过度使用的需要。
答案 1 :(得分:2)
您不仅限于传递给lambda的参数的属性。您还可以在父花括号中使用的任何对象上使用属性(在您的情况下是setter)。包括“这个”。
而不是:
NotifyPropertyChanged(m => m.AdditionalProperty);
尝试:
NotifyPropertyChanged(m => this.AdditionalProperty);
如果浏览源代码,传入的属性的字符串值是从Expression参数本身派生的。除了使用该对象获取它的属性之外,它根本不被使用。它可能来自“this”,完全是其他一些对象等等。