如何在datagrid上执行文本搜索?

时间:2013-10-01 03:06:00

标签: c# wpf datagrid wpfdatagrid

我可以知道,如何对此默认DataGrid执行搜索?虽然增加了价值。

<DataGrid Name="table" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" IsTextSearchEnabled="True" Background="White">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Timestamp" Binding="{Binding StartDate}" SortDirection="Descending" SortMemberPath="StartDate" IsReadOnly="True" />
        <DataGridTextColumn Header="Title" Binding="{Binding Title}" IsReadOnly="True" />
        <DataGridTextColumn Header="Description" Binding="{Binding Description}" IsReadOnly="True" />
        <DataGridTextColumn Header="Type" Binding="{Binding Tag}" IsReadOnly="True" />
    </DataGrid.Columns>
</DataGrid>

1 个答案:

答案 0 :(得分:2)

如何创建和使用CollectionView

以下示例说明如何创建集合视图并将其绑定到ListBox 与将其与datagrid一起使用的方式相同

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ListBox ItemsSource={Binding Customers} />
</Window>

public class CustomerView
{
   public CustomerView()
   {
        DataContext = new CustomerViewModel();
   }
}


public class CustomerViewModel
{
    private ICollectionView _customerView;

    public ICollectionView Customers
    {
        get { return _customerView; }
    }

    public CustomerViewModel()
    {
        IList<Customer> customers = GetCustomers();
        _customerView = CollectionViewSource.GetDefaultView(customers);
    }
}

<强>过滤

要过滤集合视图,您可以定义一个回调方法,以确定该项是否应该是视图的一部分。该方法应具有以下签名:bool Filter(对象项)。现在将该方法的委托设置为CollectionView的Filter属性,然后就完成了。

ICollectionView _customerView = CollectionViewSource.GetDefaultView(customers);
_customerView.Filter = CustomerFilter

private bool CustomerFilter(object item)
{
    Customer customer = item as Customer;
    return customer.Name.Contains( _filterString );
}

刷新过滤器

如果更改过滤条件并想要刷新视图,则必须在集合视图上调用Refresh()

public string FilterString
{
  get { return _filterString; }
  set 
  { 
      _filterString = value; 
      NotifyPropertyChanged("FilterString");
      _customerView.Refresh();
  }
}