问题描述
我搜索示例或示例以通过文本框过滤 WPF DataGrid 列元素.
I search an example or sample to filter the WPF DataGrid column elements by a textbox.
类似于this(给定的示例使用WPFToolkit...显然被微软抛弃了...)
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; }
}
推荐答案
您可以通过将 DataGrid 中的项绑定到支持过滤的 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
这篇关于在文本框上过滤 DataGrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!