2017-03-15 93 views
0

我有10-15列的網格。 (我通過datagrid.ItemsSource加載數據= myList.ToList())我也有textBox女巫textChanged事件。當我把這裏放在例如。 「貓」我想只看到有價值的行...貓... 我該如何做到這一點?在DataGrid中通過文本框搜索WPF

回答

1

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; } 
    } 
} 

對於這個例子中,我創建了一個動物類,但是你可以用它替換自己的類,你需要篩選。此外,我啓用了AutoGenerateColumns,但是在WPF中添加自己的列綁定仍然可以使其工作。

希望這會有所幫助!