【问题标题】:Datagrid not updated when item property for filter changes过滤器的项目属性更改时数据网格未更新
【发布时间】:2011-03-06 20:14:06
【问题描述】:
我有一个带有数据网格和按钮的简单表单。数据网格中的项目绑定到ObservableCollection 或customers。 customer 实现 INotifyPropertyChanged 接口。每个客户都有一个deleted 属性(bool 类型)。我为客户默认视图设置了一个过滤器,以根据deleted 属性过滤掉已删除的客户。到目前为止它有效。
然后,我为将选定客户标记为已删除的按钮添加一个事件。问题是设置selected_customer.deleted = true 后网格没有更新。删除的客户仍然可见。绑定到deleted 属性的列正确更新。要从网格中删除客户,我必须手动调用客户默认视图的Refresh() 方法。
当我使用ObservableCollection 并且客户实现INotifyPropertyChanged 接口时,为什么datagrid 没有自动更新?如何让它自动更新?
【问题讨论】:
标签:
wpf
datagrid
filter
observablecollection
inotifypropertychanged
【解决方案1】:
我假设您使用 CollectionViewSource 进行过滤。
下面的代码将订阅客户的 Deleted 属性的更改,并在 Deleted 更改时刷新 collectioviewsource。 Customers 是类 Customer 的 ObservableCollection。客户有一个名为 Deleted 的 bool 属性并实现了 INotifyPropertyChanged。应在填充客户之前调用 InitAutoRefresh()。
private void InitAutoRefresh(ObservableCollection<Customer> observableCollection, CollectionViewSource collectionViewSource)
{
observableCollection.CollectionChanged +=
(sender, e) =>
{
foreach(Customer newItem in e.NewItems)
{
newItem.PropertyChanged +=
(sender2, e2) =>
{
if (e2.PropertyName == "Deleted")
{
collectionViewSource.View.Refresh();
}
};
}
};
}
在填充可观察集合之前调用它。如果您在 XAML 中声明了您的 collectionViewSource,您可以使用 FindResource 来获取实例。
InitAutoRefresh(Customers, FindResource("cvsCustomers") as CollectionViewSource);