框架不支持基于 PropertyChanged 事件更新 CollectionView.Filter。有很多解决方案。
1) 在你的集合内的对象上实现IEditableObject接口,并在改变过滤器所基于的属性时调用BeginEdit和EndEdit。您可以在 Dr.WPF 的优秀博客上阅读更多相关信息:Dr.WPF 的可编辑集合
2)创建以下类并在更改的对象上使用 RefreshFilter 函数。
public class FilteredObservableCollection<T> : ObservableCollection<T>
{
public void RefreshFilter(T changedobject)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, changedobject, changedobject));
}
}
例子:
public class TestClass : INotifyPropertyChanged
{
private string _TestProp;
public string TestProp
{
get{ return _TestProp; }
set
{
_TestProp = value;
RaisePropertyChanged("TestProp");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
FilteredObservableCollection<TestClass> TestCollection = new FilteredObservableCollection<TestClass>();
void TestClass_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "TestProp":
TestCollection.RefreshFilter(sender as TestClass);
break;
}
}
在创建TestClass对象的时候订阅它的PropertyChanged事件,但是不要忘记在对象被移除的时候解开事件处理函数,否则可能会导致内存泄漏
或者
将 TestCollection 注入 TestClass 并在 TestProp 设置器中使用 RefreshFilter 函数。无论如何,这里的魔法是由 NotifyCollectionChangedAction.Replace 完成的,它完全更新了项目。