Ste*_*eve 12 collections wpf filter
我有一个绑定到CollectionViewSource的WPF ListView.它的源绑定到一个属性,如果用户选择一个选项,该属性可能会更改.
当列表视图源由于属性更改事件而更新时,所有内容都会正确更新,但视图不会刷新以考虑CollectionViewSource过滤器中的任何更改.
如果我将一个处理程序附加到Source属性绑定的Changed事件,我可以刷新视图,但这仍然是旧视图,因为绑定尚未更新列表.
有什么好的方法可以在源更改时刷新视图并重新评估过滤器?
干杯
小智 12
也许有点晚了,但这可能对其他用户有帮助,所以无论如何我都会发帖...
框架不支持基于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));
}
}
Run Code Online (Sandbox Code Playgroud)
例:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在创建TestClass对象时订阅它的PropertyChanged事件,但不要忘记在删除对象时取消挂钩事件处理程序,否则可能导致内存泄漏
要么
将TestCollection注入TestClass并使用TestProp setter中的RefreshFilter函数.无论如何,这里的魔力是由NotifyCollectionChangedAction.Replace完成的,它完全更新了项目.
您是否正在更改分配给 的实际集合实例CollectionViewSource.Source,或者您只是触发PropertyChanged它绑定到的属性?
如果Source设置了该属性,则应该为新源集合中的每个项目调用过滤器,因此我认为正在发生其他事情。您是否尝试过Source手动设置而不是使用绑定并查看是否仍然得到您的行为?
编辑:
您使用的是CollectionViewSource.View.Filter财产还是CollectionViewSource.Filter活动?当您设置新的 时,会CollectionView被吹走Source,因此,如果您Filter在 上设置了一组CollectionView,它将不再存在。
| 归档时间: |
|
| 查看次数: |
18206 次 |
| 最近记录: |