Collection properties should be read only

2019-02-18 16:59发布

I am using FxCop for my WPF MVVM assembly and it gives me the error

Collection properties should be read only

But in my property i need to RaisePropertyChangedEvent, now if i set the property to read only by removing its set section, how could i raise this event.

Syntax is somewhat like this

public List Employees
{
    get { return _employees; }
    set
    {
        if (ReferenceEquals(_employees, value))
            return;
        _employees = value;
        RaisePropertyChanged("Employees");
    }
}

标签: c# wpf mvvm
2条回答
forever°为你锁心
2楼-- · 2019-02-18 17:39

You should rarely need to raise a PropertyChanged event on a collection. Make the collection observable so that it notifies any bindings whenever items are added or removed:

public IList<Employee> Employees
{
    get; 
    private set;
}

// in your constructor:
this.Employees = new ObservableCollection<Employee>();
查看更多
The star\"
3楼-- · 2019-02-18 17:41

If you make your collection an ObservableCollection then the "important" events will be when items are added and removed from the collection, not when the collection is instatiated. I agree, with FxCop. Make the collection readonly, but make it an ObservableCollection

查看更多
登录 后发表回答