jamesIsGreen
jamesIsGreen

Reputation: 33

DataGrid filtering, multi-input, MVVM, C#

So I am having a bit of troubling figuring this out: I have a DataGrid that I am trying to filter. I am using an ICollectionView as the ItemsSource. I have a couple of ComboBoxes that I would like to narrow down the data, then I also have a TextBox I would like users to narrow down data further.

My issue is, I can get the TextBox to filter the data, and I can get the ComboBox to filter the data, but I can't get them to work together to further filter data. Only one filter works at a time.

public static string FilterText
{
   get { return _filterText; }
   set
   {
      _filterText = value;
      ICollectionView.Filter = FilterTB;
   }
}

public static Model1 PublicModelProperty
{
   get { return _publicModelProperty; }
   set
   {
      _publicModelProperty = value;
      ICollectionView.Filter = FilterCB;
   }
}

public static bool FilterTB(object names)
{
   Model2 name = names as Model2;
   if(!string.IsNullOrEmpty(FilterText))
   {
      return name.Property1.Contains(FilterText) ||
             name.Property2.Contains(FilterText);
   }
   else
   {
      return true;
   }
}

public static bool FilterCB(object names)
{
   Model2 name = names as Model2;
   if(!string.IsNullOrEmpty(PublicModelProperty.Property))
   {
      return name.Property3.Contains(PublicModelProperty.Property);
   }
   else
   {
      return true;
   }
}

Upvotes: 1

Views: 233

Answers (1)

Guillaume Ladeuille
Guillaume Ladeuille

Reputation: 84

You should filter using both FilterText and PublicModelProperty

public static string FilterText
{
   get { return _filterText; }
   set
   {
      _filterText = value;
      ICollectionView.Filter = FilterBoth;
   }
}

public static Model1 PublicModelProperty
{
   get { return _publicModelProperty; }
   set
   {
      _publicModelProperty = value;
      ICollectionView.Filter = FilterBoth;
   }
}

public static bool FilterBoth(object names)
{
    Model2 name = names as Model2;
    if (!string.IsNullOrEmpty(FilterText))
    {
        if (!name.Property1.Contains(FilterText) &&
                !name.Property2.Contains(FilterText))
            return false;
    }
    if (!string.IsNullOrEmpty(PublicModelProperty.Property))
    {
        if (!name.Property3.Contains(PublicModelProperty.Property))
            return false;
    }
    return true;
}

Upvotes: 1

Related Questions