使用此代码,我设置了我的datagrid的Itemsource。但是我得到了更多的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;
答案 0 :(得分:2)
在WPF中,在GUI元素中用作ItemsSource
的每个集合都与{{}}}相关联。
ICollectionView
具有ICollectionView
属性,其类型为Predicate<object>
。
如果您设置此Filter
并在之后调用Filter
,则DataGrid会自行更新为仅显示Filter
返回true的项目。
如何使用它的示例:
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();
答案 1 :(得分:0)
您可以在课程字段中保存已加载的数据,然后通过句柄按钮过滤它:
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 pattern是WPF的标准事实,它对您的应用非常有用。