2

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)?

Community
  • 1
  • 1
Jason D
  • 2,634
  • 6
  • 33
  • 67

1 Answers1

0

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Worker implements `Observable Object` via MVVM Light. – Jason D Jul 24 '13 at 23:35
  • 1
    @ReedCopsey I think, what the OP wants is to see the change of EmployerID on the WorkersEmployed collection automatically (such as [Linq to ObservableCollection](http://linq2obscollection.codeplex.com/) or [Bindable LINQ](http://bindablelinq.codeplex.com/)). – Cédric Bignon Jul 24 '13 at 23:35
  • I may have to look into `ICollectionView` again. I explored it awhile ago but from what I can recall, I never did find a way for it to refresh itself automatically. I'm looking for a more 'hands-off' approach. However, if there is a way to have an `ICollectionView` update/refresh itself automatically, please let me know. I would switch to that in a heartbeat. – Jason D Jul 24 '13 at 23:46