[英]search in DataGrid by textBox WPF
我有 10-15 列的网格。 (我通过 datagrid.ItemsSource = myList.ToList() 加载数据)我还有 textBox 女巫 textChanged 事件。 当我放在这里时,例如。 “猫”我只想看到有值的行...猫...我该怎么做?
LINQ 查询非常适合这类事情,概念是创建一个变量来存储所有行(在名为_animals
的示例中),然后当用户按下文本框中的键时使用查询,并将结果作为ItemsSource
代替。
下面是一个基本的工作示例,说明它是如何工作的,首先是窗口的 XAML。
<Window x:Class="FilterExampleWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:FilterExampleWPF"
mc:Ignorable="d"
WindowStartupLocation="CenterScreen"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox x:Name="textBox1" Height="22" Margin="10,10,365,0" VerticalAlignment="Top" KeyUp="textBox1_KeyUp" />
<DataGrid x:Name="dataGrid1" Height="272" Margin="10,40,10,0" VerticalAlignment="Top" AutoGenerateColumns="True" />
</Grid>
</Window>
接下来是后面的代码:
using System.Collections.Generic;
using System.Linq;
namespace FilterExampleWPF
{
public partial class MainWindow : System.Windows.Window
{
List<Animal> _animals;
public MainWindow()
{
InitializeComponent();
_animals = new List<Animal>();
_animals.Add(new Animal { Type = "cat", Name = "Snowy" });
_animals.Add(new Animal { Type = "cat", Name = "Toto" });
_animals.Add(new Animal { Type = "dog", Name = "Oscar" });
dataGrid1.ItemsSource = _animals;
}
private void textBox1_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
var filtered = _animals.Where(animal => animal.Type.StartsWith(textBox1.Text));
dataGrid1.ItemsSource = filtered;
}
}
public class Animal
{
public string Type { get; set; }
public string Name { get; set; }
}
}
对于本示例,我创建了一个 Animal 类,但是您可以将其替换为您需要过滤的自己的类。 我还启用了 AutoGenerateColumns,但是在 WPF 中添加您自己的列绑定仍然允许它工作。
希望这可以帮助!
这是我的解决方案。
public class Animal
{
public string Type { get; set; }
public string Name { get; set; }
}
List<Animal> _animals = new List<Animal>();
public MainWindow()
{
InitializeComponent();
_animals.Add(new Animal { Type = "cat", Name = "Snowy" });
_animals.Add(new Animal { Type = "cat", Name = "Toto" });
_animals.Add(new Animal { Type = "dog", Name = "Oscar" });
dataGrid1.ItemsSource = _animals;
}
List<Animal> filterModeLisst = new List<Animal>();
private void searchBox_TextChanged(object sender, TextChangedEventArgs e)
{
filterModeLisst.Clear();
if (searchBox.Text.Equals(""))
{
filterModeLisst.AddRange(_animals);
} else
{
foreach (Animal anim in _animals)
{
if (anim.Name.Contains(searchBox.Text))
{
filterModeLisst.Add(anim);
}
}
}
dataGrid1.ItemsSource = filterModeLisst.ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.