Notify Property Changed Event without setter

2019-08-12 06:53发布

I am developing a WPF application using MVVM architect, and as a common scenario using properites to Notify Changes like

public List<EmployeeInfo> Employees
    {
            get
            {
                return _employees;
            }
            set
            {
                _employees = value;
                NotifyPropertyChanged(() => Employees);
            }
        }

My only issue is that i am using property setter to notify application about the changes made to some value, and according to FxCop this is a bad practice and 'CollectionPropertiesShouldBeReadOnly'. So i want to improve a little bit on that, so tell me some mechanism with which i could use Notify Property changed without using setter.

标签: c# wpf mvvm
3条回答
Bombasti
2楼-- · 2019-08-12 07:19

The ObservableCollection itself informs about changes happened. So you don't need to raise the PropertyChanged Event. If you think, that it's necessary tho change the collection, then you can delete and add items. Due to the observable pattern, the changes will be anounced.

查看更多
冷血范
3楼-- · 2019-08-12 07:33

The fact that you are using a setter means you're trying to replace the instance of the collection with a new object instance. If you just are worried about changes to items in the collection, that's already built into the observablecollection. FxCop is going to complain about the setter whether you had the notifypropertychanges call or not.

查看更多
霸刀☆藐视天下
4楼-- · 2019-08-12 07:38

If your collection property is read-only, you don't need to notify anything that the entire collection has changed to a different one - instead, the event handlers on the collection will be notified of changes within the collection (the addition of items etc).

If you need to be able to change which collection the property refers to within the view model, you could always make the setter private and keep the existing notification mechanism.

查看更多
登录 后发表回答