简体   繁体   中英

Raise CollectionChanged in ObservableCollection when an item's property is modified

I am trying to bind the results of a LINQ query of an ObservableCollection to my UI and I seem to have it halfway working. If I add a new item to the ObservableCollection , I can raise CollectionChanged and call PropertyChanged on the property and it will update. Unfortunately, modifying a property of an item doesn't cause CollectionChanged to fire and I can't figure out how to make it fire. I have tried methods that others have posted such as TrulyObservableColection with no luck. Is there any way to force CollectionChanged to fire? Or is there another route I can take in this situation. I would rather not have to abandon LINQ. Any advice would be appreciated.

private ObservableCollection<Worker> _workers = new ObservableCollection<Worker>();
public ObservableCollection<Worker> Workers
{
    get { return _workers; }
}

public IEnumerable<Worker> WorkersEmployed
{
    get { return GameContainer.Game.Workers.Where(w => w.EmployerID == this.ID); }
}

GameContainer.Game.Workers.CollectionChanged += Workers_CollectionChanged;

private void Workers_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    RaisePropertyChanged(() => WorkersEmployed);
}

This works assuming a new entry is added to the collection. How can I achieve the same result when an item is simply modified (such as Workers' EmployerID in this case)?

How can I achieve the same result when an item is simply modified (such as Workers' EmployerID in this case)?

You would need to subscribe to the property changed on each worker, and raise the appropriate PropertyChanged event on the resulting collection.

Another option, however, would be to use WPF's built in ICollectionView filtering instead of exposing a separate property.

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