i++

プログラム系のメモ書きなど

WPF/XAML : DataGrid の表示内容を TextBox への入力内容でフィルタリングする

ポイントは以下の3点です。

  • DataGrid の ItemsSource に CollectionViewSource.View を使う
  • CollectionViewSource.Filter にフィルタリング用の関数を登録する
  • TextBox の入力に変更がある度に CollectionViewSource.View.Refresh() を呼ぶ

サンプルコード

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

private ObservableCollection<Person> mPersonObservableCollection;
private CollectionViewSource mPersonCollectionViewSource;

public MainWindow()
{
    InitializeComponent();

    // この辺りで DataGrid のソースとフィルター関数を登録
    mPersonObservableCollection = new ObservableCollection<Person>();
    mPersonCollectionViewSource = new CollectionViewSource();
    mPersonCollectionViewSource.Filter += Person_Filter;
    mPersonCollectionViewSource.Source = mPersonObservableCollection;
    PersonDataGrid.ItemsSource = mPersonCollectionViewSource.View
}

private void Person_Filter(object sender, FilterEventArgs e)
{
    if (e.Item != null)
    {
        // テキストが空の時はフィルタリングなし
        if (String.IsNullOrEmpty(PersonFilterTextBox.Text))
        {
            e.Accepted = true;
        }
        else
        {
            // 部分一致を受け入れる
            Person p = e.Item as Person;
            e.Accepted = p.Name.Contains(PersonFilterTextBox.Text);
        }
    }
}