gpt4 book ai didi

windows-runtime - Metro App CollectionViewSource ObservableCollection 过滤器

转载 作者:行者123 更新时间:2023-12-04 07:00:28 33 4
gpt4 key购买 nike

似乎在 WinRT 中无法使用 CollectionViewSource 过滤 ObservableCollection:

See here!

我可以使用 LINQ 进行过滤,但是如果发生影响过滤数据的更改,我如何让 UI 更新?

最佳答案

我最终编写了自己的类来达到预期的效果:

public class ObservableCollectionView<T> : ObservableCollection<T>
{
private ObservableCollection<T> _view;
private Predicate<T> _filter;

public ObservableCollectionView(IComparer<T> comparer)
: base(comparer)
{

}

public ObservableCollectionView(IComparer<T> comparer, IEnumerable<T> collection)
: base(comparer, collection)
{

}

public ObservableCollectionView(IComparer<T> comparer, IEnumerable<T> collection, Predicate<T> filter)
: base(comparer, collection == null ? new T[] { } : collection)
{
if (filter != null)
{
_filter = filter;

if (collection == null)
_view = new ObservableCollection<T>(comparer);
else
_view = new ObservableCollection<T>(comparer, collection);
}
}

public ObservableCollection<T> View
{
get
{
return (_filter == null ? this : _view);
}
}

public Predicate<T> Filter
{
get
{
return _filter;
}
set
{
if (value == null)
{
_filter = null;
_view = new ObservableCollection<T>(Comparer);
}
else
{
_filter = value;
Fill();
}
}
}

private void Fill()
{
_view = new ObservableCollection<T>(Comparer);
foreach (T item in this)
{
if (Filter(item))
View.Add(item);
}
}

private int this[T item]
{
get
{
int foundIndex = -1;
for (int index = 0; index < View.Count; index++)
{
if (View[index].Equals(item))
{
foundIndex = index;
break;
}
}
return foundIndex;
}
}

protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
base.OnCollectionChanged(e);

if (_filter != null)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (T item in e.NewItems)
if (Filter(item))
View.Add(item);
break;

case NotifyCollectionChangedAction.Move:

break;

case NotifyCollectionChangedAction.Remove:
foreach (T item in e.OldItems)
if (Filter(item))
View.Remove(item);
break;

case NotifyCollectionChangedAction.Replace:
for (int index = 0; index < e.OldItems.Count; index++)
{
T item = (T)e.OldItems[index];
if (Filter(item))
{
int foundIndex = this[item];
if (foundIndex != -1)
View[foundIndex] = (T)e.NewItems[index];
}
}
break;

case NotifyCollectionChangedAction.Reset:
Fill();
break;
}
}
}

protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);

if (_filter != null)
{
// TODO: Implement code for property changes
}
}
}

还不完善。因此,欢迎提出改进/建议。

您现在可以使用 View 属性将此对象直接绑定(bind)到控件。

关于windows-runtime - Metro App CollectionViewSource ObservableCollection 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16244596/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com