在文本框中过滤数据网格 [英] Filter a DataGrid on a Text box

查看:77
本文介绍了在文本框中过滤数据网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索一个示例或示例以通过文本框过滤WPF DataGrid列元素。

I search an example or sample to filter the WPF DataGrid column elements by a textbox.

类似于(给定示例使用了 WPFToolkit ...显然被Microsoft放弃了...)

Something similar to this (the given example uses a WPFToolkit... apparently abandoned by Microsoft...)

XAML

<Canvas>
    <DataGrid Height="200" Name="dataGrid1" Width="200" Canvas.Top="23" />
    <TextBox  Name="textBox1" Width="120" />
</Canvas>

cs:

public partial class MainWindow : Window
{
    private List<Personne> persons;
    ICollectionView cvPersonnes;

    public MainWindow()
    {
        InitializeComponent();

        persons = new List<Personne>();

        persons.Add(new Personne() { Id = 1, Nom = "Jean-Michel", Prenom = "BADANHAR" });
        persons.Add(new Personne() { Id = 1, Nom = "Gerard", Prenom = "DEPARDIEU" });
        persons.Add(new Personne() { Id = 1, Nom = "Garfild", Prenom = "THECAT" });
        persons.Add(new Personne() { Id = 1, Nom = "Jean-Paul", Prenom = "BELMONDO" });

        cvPersonnes = CollectionViewSource.GetDefaultView(persons);

        if (cvPersonnes != null)
        {
            dataGrid1.AutoGenerateColumns = true;
            dataGrid1.ItemsSource = cvPersonnes;
            cvPersonnes.Filter = TextFilter;
        }
    }

    public bool TextFilter(object o)
    {
        Personne p = (o as Personne);
        if (p == null) 
            return false;

        if (p.Nom.Contains(textBox1.Text))
            return true;
        else
            return false;
    }

}

public class Personne
{
    public int Id { get; set; }
    public string Nom { get; set; }
    public string Prenom { get; set; }
}


推荐答案

您可以过滤项目通过将其绑定到支持过滤的 ICollectionView 在数据网格中。

You can filter the Items in the DataGrid by binding it to an ICollectionView that supports filtering.

详细信息此处适用于.NET 4。 .NET 4.5相同,但似乎文档已丢失。有一小段提及在分组,排序和筛选标题下。

Details here for .NET 4. The process is the same for .NET 4.5, but it seems the documentation has been lost. There's a small mention to it here under the "Grouping, Sorting, and Filtering" heading.

编辑:在撰写本文时,WPF工具包并未被微软。 此处

edit: at the time this was originally written, the WPF toolkit had not been abandoned by Microsoft. The controls that used to be part of it are now in the framework, and the toolkit was alive and doing well here

这篇关于在文本框中过滤数据网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆