wpf 筛选项目源

bihw5rsg  于 2022-11-18  发布在  其他
关注(0)|答案(2)|浏览(173)

通过这段代码,我设置了datagrid的ItemsSource。但是我有更多的wpf控件需要过滤datagrid,例如从时间范围。我可以为此写一个新的查询,但这似乎是不必要的,因为数据已经可用,我只需要过滤它。什么是最好的方法来做到这一点?
如果能得到任何帮助,我将不胜感激!

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;
cigdeys3

cigdeys31#

在WPF中,在GUI元素中用作ItemsSource的每个集合都有一个与之关联的ICollectionView
ICollectionView具有Filter属性,其类型为Predicate<object>
如果设置此Filter并在之后调用Refresh(),则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();
xesrikrc

xesrikrc2#

您可以将加载的数据保存在类字段中,然后通过句柄按钮进行过滤单击:

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的事实上的标准,它对您的应用程序很有用。

相关问题