在多种情况下无法进行过滤

时间:2018-07-26 14:06:39

标签: c# wpf foreach filtering collectionviewsource

我正在编写一个WPF应用程序,该程序将虚拟数据加载到数据网格中。数据网格包含以下数据模型:

public class CharacterCollection
  {
    public string Name { get; set; }
    public int Level { get; set; }
    public string Race { get; set; }
    public string Class { get; set; }

    public List<CharacterCollection> GetCharacters()
    {
      List<CharacterCollection> characters = new List<CharacterCollection>();
      characters.Add(new CharacterCollection { Name = "Lothar", Class = "Fighter", Race = "Human", Level = 5 });
      characters.Add(new CharacterCollection { Name = "Turk", Class = "Barbarian", Race = "Half-Orc", Level = 3 });
      characters.Add(new CharacterCollection { Name = "Melian", Class = "Cleric", Race = "Elf", Level = 10 });
      //... there's about 16 more entries, but you get the idea ;)
      return characters;
    }

接下来,我添加了4个组合框;每个填充有CharacterCollection中的属性之一

public partial class MainWindow : Window
{
    private CharacterCollection _characters = new CharacterCollection();
    List<CharacterCollection> collection = new List<CharacterCollection>();

    public MainWindow()
    {
      InitializeComponent();

      collection = _characters.GetCharacters();
      dgCharacterChart.ItemsSource = collection;

      var characterNames = collection.Select(c =>c.Name).Distinct().ToList();
      foreach(var item in characterNames)
      {
        CheckBox cb = new CheckBox();
        cb.Content = item.ToString();

        cbName.Items.Add(cb);
      }
      //...the other 3 combo boxes are filled the same way. I know its ugly and I will work on abstracting this a little better :)
   }
}

到目前为止,我得到的是4个组合框,其中装有复选框,用户可以检查想要的框有多少个。这些将用于过滤。

最后,我有一个过滤器按钮...

private void btnFilter_Click(object sender, RoutedEventArgs e)
{
      ICollectionView _characterCollection = CollectionViewSource.GetDefaultView(collection);
      var predicates = new List<Predicate<CharacterCollection>>();

      foreach (CheckBox checkbox in cbName.Items)
      {
        if (checkbox.IsChecked == true)
        {
          predicates.Add(new Predicate<CharacterCollection>(x => x.Name == checkbox.Content.ToString()));
        }
      }

      foreach (CheckBox checkbox in cbClass.Items)
      {
        if (checkbox.IsChecked == true)
        {
          predicates.Add(new Predicate<CharacterCollection>(x => x.Class == checkbox.Content.ToString()));
        }
      }

      foreach (CheckBox checkbox in cbLevel.Items)
      {
        if (checkbox.IsChecked == true)
        {
          predicates.Add(new Predicate<CharacterCollection>(x => x.Level == Convert.ToInt32(checkbox.Content)));
        }
      }

      foreach (CheckBox checkbox in cbRace.Items)
      {
        if (checkbox.IsChecked == true)
        {
          predicates.Add(new Predicate<CharacterCollection>(x => x.Race == checkbox.Content.ToString()));
        }
      }
      _characterCollection.Filter = o =>
      predicates.All(predicate => predicate(o as CharacterCollection));
      dgCharacterChart.ItemsSource = _characterCollection;
 }

当我单击仅选择一个字段的按钮时,例如从名称组合框中说出来,它的过滤效果就很好。但是,如果我从名称中选择了多个选项,或者开始从其他组合框中检查多个条目,则我的数据网格将显示为空白。当我调试代码时,我可以看到我的谓词列表包含所有标记为已选中但条目计数为0的条目。有人可以帮我弄清楚为什么我得到这些结果吗?

非常感谢。

1 个答案:

答案 0 :(得分:1)

我做了类似的事情,但是我通过文本框进行了过滤。可能会对您有帮助。

.Xaml如下

 <TextBox FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"
                                     Background="{x:Null}"
                                     Text="{Binding Item , UpdateSourceTrigger=LostFocus}" Margin="6,0,0,0" BorderThickness="0" PreviewKeyDown="ItemField_PreviewKeyDown" TextChanged="ItemField_TextChanged" IsReadOnly="{Binding IsReadonly}" />

.Xaml.cs如下

private ObservableCollection<ItemGrid> _itemGrid = new ObservableCollection<ItemGrid>();
    public ObservableCollection<ItemGrid> ItemGrid
    {
        get
        {
            return _itemGrid;
        }
        set
        {
            _itemGrid = value;


        }
    }

    private void ItemField_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (isBeginingEdit) return;
        //here we show the item selector and take care of autocomplete
        var textBox = sender as TextBox;
        if (textBox.Text != "")
        {
            var _itemSourceList = new CollectionViewSource() { Source = ItemGrid };
            ICollectionView Itemlist = _itemSourceList.View;
            ItemSearchText = textBox.Text;
            Itemlist.Filter = ItemFilter;
            var count = _itemSourceList.View.Cast<ItemGrid>().Count();
            if (count > 0)
            {
                ItemsGrid.ItemsSource = Itemlist;
            } 
        } 
   }