WPF:更新私有setter变量IS不会引发propertyChanged事件处理程序

时间:2014-11-10 12:06:27

标签: c# wpf mvvm

我的视图模型具有以下代码。我正在使用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函数时它才会被提升。不应该更新私有变量引发属性更改事件吗?

2 个答案:

答案 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指定值。