我的视图模型具有以下代码。我正在使用MVVMLIght
class SettingsViewModel : ViewModelBase
{
public SettingsViewModel()
{ }
string _customerName;
public string customerName
{
get
{
return _customerName;
}
set
{
if (_customerName == value)
return;
_customerName = value;
RaisePropertyChanged("customerName");
}
}
private void _changeNamePrivate()
{
this._customerName = "SomePrivateName";
}
private void _changeNamePublic()
{
this.customerName = "SomePublicName";
}
}
我的问题是,当我调用_changeNamePrivate
时,RaisePropertyChanged
事件处理程序未被引发。但只有在我调用_changeNamePublic
函数时它才会被提升。不应该更新私有变量引发属性更改事件吗?
答案 0 :(得分:1)
_customerName
是一个字段,而不是属性。当您为其分配内容时,它会直接写入存储位置,但不会执行任何其他代码。另一方面,customerName
是一个属性:当你为它指定一些东西时,它会执行属性setter,这会引发事件。
答案 1 :(得分:0)
正如@dkozl和@Ben已经说过,这是预期的:
您提供的代码只会在RaisePropertyChanged
属性的set部分中调用customerName
事件处理程序:
public string customerName
{
get
{
return _customerName;
}
set
{
if (_customerName == value)
return;
_customerName = value;
RaisePropertyChanged("customerName");
}
}
因此,在_changeNamePublic()
中,它会更改属性的值,以便调用set部分并引发RaisePropertyChanged
处理程序。与_changeNamePrivate()
中的位置一样,它仅为字段_customerName
指定值。