是否需要在WPF MVVM中对ICommand类型的属性使用INotifyPropertyChanged? [英] It is necessary to use INotifyPropertyChanged on properties of type ICommand in WPF MVVM?
问题描述
这两个变量之间是否存在差异(性能,内存泄漏或准则)?
Is there a difference between this two variants (performance, memory leaks or guidelines)?
使用NPC:
private ICommand mGoBackCommand;
public ICommand GoBackCommand
{
get { return mGoBackCommand; }
set
{
if (mGoBackCommand != value)
{
mGoBackCommand = value;
RaisePropertyChanged("GoBackCommand");
}
}
}
自动属性:
public ICommand GoBackCommand {get; set;}
UPD: 最后一个问题是: 如果自动属性是在构造函数中分配一次的简单命令,是否可以在VievModel中使用自动属性,或者由于性能,内存泄漏或其他原因而需要在VM的每个属性上实现NPC?
UPD: Final question is: Can I use auto properties in VievModel if they are simple commands which will be assigned once in constructor, or I need implement NPC on each property of the VM because of performance, memory leaks or something else?
推荐答案
如果您正在编写实现INotifyPropertyChanged
的类,则您正在签订的合同规定:任何属性更改时,我都会引发PropertyChanged
事件."
If you are writing a class that implements INotifyPropertyChanged
, you are making a contract that says "I'll raise the PropertyChanged
event when any property changes."
但是,如果您知道某个属性在实例的生存期内不会更改,那么您可以通过不为该属性提高PropertyChanged
来琐碎地满足该合同.
But, if you know for a fact that a property won't change during the lifetime of the instance, then you trivially satisfy that contract by never raising PropertyChanged
for that property.
因此,如果您在构造函数中一次设置了一个属性(设置为它忘记了"属性),那么您就不必只为了支持INotifyPropertyChanged
而修改该属性,并且可以使用自动实现的财产.但是,在这种情况下,您应该从此更改属性:
So, if you set a property once in the constructor (a "set it a forget it" property), then you don't need to mangle the property just to support INotifyPropertyChanged
and you can use an auto-implemented property. However, in this you should change the property from this:
public ICommand GoBackCommand { get; set; }
对此:
public ICommand GoBackCommand { get; private set; }
以免在课堂外意外修改它.
so that it cannot be accidentally modified outside the class.
这篇关于是否需要在WPF MVVM中对ICommand类型的属性使用INotifyPropertyChanged?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!