通过文本框 WPF 在 DataGrid 中搜索

sla*_*eke 2 c# grid search datagrid textbox

我有 10-15 列的网格。(我通过 datagrid.ItemsSource = myList.ToList() 加载数据)此外,我还有 textBox 女巫 textChanged 事件。当我放在这里时,例如。“cat” 我只想查看具有值 ...cat... 的行 我该怎么做?

Kod*_*oid 6

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>
Run Code Online (Sandbox Code Playgroud)

接下来是后面的代码:

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

对于本示例,我创建了一个 Animal 类,但是您可以将其替换为您自己需要过滤的类。此外,我还启用了 AutoGenerateColumns,但是在 WPF 中添加您自己的列绑定仍然允许其工作。

希望这可以帮助!