筛选项目源
本文关键字:项目 筛选 | 更新日期: 2023-09-27 18:37:18
使用此代码,我正在设置数据网格的ItemsSource。但是,我需要更多 wpf 控件来筛选数据网格,例如从时间范围。我可以为此编写一个新查询,但这似乎没有必要,因为数据已经可用,我只需要过滤它。最好的方法是什么?
我能得到的任何帮助将不胜感激!
DateTime dateStart = CalenderSearch.SelectedDates.First();
DateTime dateEnd = CalenderSearch.SelectedDates.Last();
ObjectQuery<Fouten> fouten = eventsEntities.Foutens;
var query =
(from fout in fouten
where dateStart <= fout.Datum && dateEnd >= fout.Datum && fout.Rapporten.Treinen.NameTrein == trein.NameTrein
orderby fout.Datum, fout.Time
select new
{
Datum = fout.Datum,
Time = fout.Time,
FoutCode = fout.FoutCode,
Omschrijving = fout.Omschrijving,
Teller = fout.Teller,
Module = fout.Module,
FoutId = fout.FoutId
}).AsEnumerable().Select(x => new Fouten
{
Datum = x.Datum,
Time = x.Time,
FoutCode = x.FoutCode,
Omschrijving = x.Omschrijving,
Teller = x.Teller,
Module = x.Module,
FoutId = x.FoutId
}).ToList();
if (query.Count == 0)
foutensDataGrid.ItemsSource = null;
else
foutensDataGrid.ItemsSource = query;
在 WPF 中,用作 GUI 元素中ItemsSource
的每个集合都有一个与之关联的ICollectionView
。
ICollectionView
具有 Filter
属性,该属性的类型为 Predicate<object>
。
如果设置此Filter
并在之后调用Refresh()
,则 DataGrid 将自行更新,以仅显示返回 true Filter
的项目。
如何使用它的示例:
var collectionView = CollectionViewSource.GetDefaultView(foutensDataGrid.ItemsSource);
collectionView.Filter = o => {
var fouten = o as Fouten;
//do your filtering, e.g.
return fouten.Datum <= dateEnd && fouten.Datum >= dateStart;
}
collectionView.Refresh();
您可以将加载的数据保存在类字段中,然后通过句柄按钮对其进行过滤点击:
public class YourView
{
private List<Fouten> loadedData;
public void LoadData(...)
{
ObjectQuery<Fouten> fouten = eventsEntities.Foutens;
// here you save unfiltered data to the field and then you can use it to filter collection
loadedData = ...;
// if you want to filter values immediately you can call filter method right here
// FilterByFoutCode(someValue);
if (loadedData.Count == 0)
foutensDataGrid.ItemsSource = null;
else
foutensDataGrid.ItemsSource = loadedData;
}
private void FilterByFoutCodeButtonClick(object sender, EventArgs e)
{
var filter = FoutCodeTextBox.Content.ToString();
if(!string.IsNullOrEmpty(filter))
{
// if your filter is not empty then filter loadedData by criteria
FilterByFoutCode(filter);
}
}
private void FilterByFoutCode(string filter)
{
foutensDataGrid.ItemsSource = loadedData.Where(x => x.FoutCode == filter);
}
}
此外,在性能上下文中,您不应该通过 select new {...}
、.AsEnumerable()
和 Select(...)
对集合进行额外的迭代,只需在 LINQ 查询后立即调用ToList()
即可。
最后,MVVM 模式是 WPF 的标准事实,它对你的应用很有用。