简体   繁体   English

什么时候需要使用自动属性,什么时候属性需要更改property?

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

I am using wpf and its C sharp! 我正在使用wpf及其C语言!

I have this in my Animal.cs clas 我的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;} 公共字符串AnimalName {get; set;}

There is no difference in binding and validation. 绑定和验证没有区别。 Everythings works as before when I exchange the code. 交换代码时,Everything仍像以前一样工作。

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"); 所以我需要调用propertyChanged(“ AnimalName”); only when I want to change its property value? 仅当我想更改其属性值时?

I am ac# beginner ;) 我是ac#初学者;)

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. 如果您的对象具有将绑定到控件的可更新属性(setter),则您需要确保通过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. 但是,如果您具有只读属性和/或不打算在数据绑定方案中使用的属性,那么您就不必在该属性的设置器内实现或调用NotifyPropertyChanged方法,在这种情况下,您可以使用自动属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 何时使用自动属性? - When to use automatic properties? 当我在INotifyPropertyChanged上引发PropertyChanged事件时出错 - Error when I raised the PropertyChanged event on INotifyPropertyChanged 当BindingList元素的属性更改时,缺少PropertyChanged事件 - Missing PropertyChanged event when BindingList elements has properties changed 当我使用 PropertyChanged 时,WPF ItemsControl 不刷新 - WPF ItemsControl doesn't refresh when I use PropertyChanged WPF何时订阅PropertyChanged事件? - When does WPF subscribe to the PropertyChanged event? 当有封闭时我是否需要使用互锁? - Do I need to use interlocked when there is a closure? 我什么时候需要使用ViewState - When do I need to use ViewState 在 Winform 中,为什么当我在一个数据源上调用 PropertyChanged 时所有绑定的属性都会更新? - In Winform why ALL bound properties are updated when I call PropertyChanged on ONE data source? 我什么时候需要在图形上使用dispose()? - When do I need to use dispose() on graphics? 在C#中写入事件日志 - 在写入应用程序日志时是否需要使用EventLog.CreateEventSource? - Writing to event log in C# - do I need to use EventLog.CreateEventSource when writing to Application log?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM