c# - 通过文本框 WPF 在 DataGrid 中搜索

标签 c# search datagrid textbox grid

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

最佳答案

LINQ 查询适用于此类事情,概念是创建一个变量来存储所有行(在名为 _animals 的示例中),然后当用户按下文本中的某个键时框使用查询,并将结果作为 ItemsSource 传递。

这是一个基本的工作示例,说明它是如何工作的,首先是 Window 的 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 中添加您自己的列绑定(bind)仍然允许它工作。

希望这对您有所帮助!

关于c# - 通过文本框 WPF 在 DataGrid 中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42821518/

相关文章:

c# - 按名称 (ID) C# for ASP.NET 查找文本框

c# - 在 C# 中,是否可以在不打开浏览器的情况下在后台打开 URL?

search - 在 vi/vim 中,是否可以创建一个映射来将单词连接到动态搜索?

WPF DataGrid - 创建一个新的自定义列

c# - 如何在到另一点的路径上找到最近的位置

javascript - 精确字符串匹配文件名数组 JavaScript/Nodejs

php - 使用 Elasticsearch 在 Laravel 中搜索查询背后的逻辑

c# - WPF数据网格按所选列自动排序

c# - WPF C# 数据网格对象引用未设置为对象的实例

C#根据输入参数从url下载zip文件