2017-03-15 11 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> 

次の背後にあるコード:私はAnimalクラスを作成した。この例

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で独自の列バインディングを追加しても、これは動作することができます。

希望すると便利です。

関連する問題