在ObservableCollection中使用where子句

时间:2011-03-03 14:49:11

标签: .net 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;

我有主列表_Organizations我希望_OrganizationManagement包含“DealerGroup”的过滤列表。

但问题是使用上面的_Organizations和_OrganizationManagement是不同步的,在这个代码之后我在_Organizations中添加它没有添加_OrganizationManagement我所理解的我们用new ObservableCollection过滤它所以新实例传递给_OrganizationManagement < / p>

1 个答案:

答案 0 :(得分:1)

您必须订阅_Organizations的CollectionChanged事件并刷新_OrganizationManagement。要保留绑定,请使用以下内容:

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);
}