gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:20:55 31 4
gpt4 key购买 nike

我有 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com