【问题标题】:can i search in itemsource and bind again to listview?我可以在 itemsource 中搜索并再次绑定到 listview 吗?
【发布时间】:2018-04-13 08:50:34
【问题描述】:

每次用户在文本框中键入我运行新查询时,我都有用于在列表视图中搜索的列表视图和文本框,有没有更好的方法来做到这一点?无需仅从 itemsources 从数据库运行查询?

private void txtEditSearch_TextChanged(object sender, TextChangedEventArgs e)
{
    if (txtEditSearch.Text != string.Empty)
    {
         var query = GetAllSchoolsAsync(txtEditSearch.Text);
         query.Wait();

         List<DataClass.Tables.School> data = query.Result;
         if (data.Any())
              dgv.ItemsSource = data;
     }
     else
        getSchool();
} 

我需要这样的东西:

var basedata = dgv.Itemsource;
dgv.ItemSource = basedata.where(x=>x.Name == txtEditSearch.Text).Select(x=>x);

【问题讨论】:

  • 为什么不从数据库中查询所有记录一次?然后你在这个源上执行你的过滤器。

标签: c# wpf linq listview


【解决方案1】:

如果列表视图中填充了数据,您可以过滤该数据,就像搜索一样,只显示您要求的数据。这是我从中了解到的链接:

http://www.wpf-tutorial.com/listview-control/listview-filtering/

【讨论】:

    【解决方案2】:

    我建议您实现此目的的最佳方法是创建一个初始的未过滤集合并从此集合中过滤。

    创建一个私有字段来存储初始 School 项目:

    private List<DataClass.Tables.School> _initialCollection;
    

    用构造函数中未过滤的项目填充它:

    public MyView()
    {
      var query = GetAllSchoolsAsync();
      query.Wait();
      _initialCollection = query.Result;      
    }
    

    在 TextChanged 事件处理程序中,您可以将过滤添加到 ListView 的 ItemSource:

    private void txtEditSearch_TextChanged(object sender, TextChangedEventArgs e)
    {
      dgv.ItemSource = _initialCollection.Where(x=>x.Name == txtEditSearch.Text).Select(x=>x);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 2023-03-06
      相关资源
      最近更新 更多