SOF User
SOF User

Reputation: 7830

using where clause in ObservableCollection

   private ObservableCollection<OrganizationUnit> _Organizations = new ObservableCollection<OrganizationUnit>();
   private ObservableCollection<OrganizationUnit> _OrganizationManagement;

_OrganizationManagement = new ObservableCollection<OrganizationUnit>(_Organizations.Where(p => p.Type == "DealerGroup").ToList());
            GridOrganizationManagement.ItemsSource = _OrganizationManagement;

I have main list _Organizations I want that _OrganizationManagement contains filter list of "DealerGroup".

But problem is using above _Organizations and _OrganizationManagement are not sync when after this code I add value in _Organizations it doesnot add in _OrganizationManagement what i have understand we are filtering it with new ObservableCollection so new instance is pass to _OrganizationManagement

Upvotes: 0

Views: 4654

Answers (1)

Vincent Vancalbergh
Vincent Vancalbergh

Reputation: 3337

You'll have to subscribe to the CollectionChanged event of _Organizations and refresh _OrganizationManagement. To preserve the bindings use something like this:

private ObservableCollection<OrganizationUnit> _Organizations = new ObservableCollection<OrganizationUnit>();
private ObservableCollection<OrganizationUnit> _OrganizationManagement;

GridOrganizationManagement.ItemsSource = _OrganizationManagement;

_Organisations.CollectionChanged += (s,e) =>
{
    var newlist = new ObservableCollection<OrganizationUnit>(_Organizations.Where(p => p.Type == "DealerGroup").ToList());
    _OrganizationManagement.Clear();
    foreach(var o in newlist)
        _OrganizationManagement.Add(o);
}

Upvotes: 1

Related Questions