简体   繁体   中英

When do I need to use automatic poperties and when properties with propertychanged event?

I am using wpf and its C sharp!

I have this in my Animal.cs clas

private string _animalName;

    public string AnimalName
    {
        get { return _animalName; }
        set
        {
            if(_animalName!= value)
            {
                _animalName= value;
                this.NotifyPropertyChanged("AnimalName");
            }
        }
    }

I could also write:

public string AnimalName {get;set;}

There is no difference in binding and validation. Everythings works as before when I exchange the code.

Is this due to the fact that I only create new animals but I do not allow to update the animals name in my application ?

So I need to call the propertyChanged("AnimalName"); only when I want to change its property value?

I am ac# beginner ;)

If your object has an updateable property (setter) that will be bound to a control then you need to ensure to let the bound control know of any changes to that property via INotifyPropertyChanged. However, if you have a readonly property and/or a property that's not going to be used in a data-binding scenario then you don't care about implementing or calling NotifyPropertyChanged method from within that property's setter in which case you can use automatic properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM