如何为DataGrid WPF创建复杂的筛选器

时间:2018-12-24 10:56:08

标签: c# wpf datagrid

我想为4个字段创建filrer。但是我得到了太多的代码。 当只选择一个字段或同时选择几个(2,3或4)字段时,我需要过滤器。如何为其创建逻辑?

我的丑陋代码:

void ViewSource_Filter(object sender, FilterEventArgs e)
{
if (e.Item is Event evnt)
{

    bool selectedModel = filterEventsControl.ComboBoxModels.SelectedIndex != 0 && filterEventsControl.ComboBoxModels.SelectedItem != null;
    bool selectedIp = filterEventsControl.ComboBoxIPs.SelectedIndex != 0 && filterEventsControl.ComboBoxIPs.SelectedItem != null;
    bool selectedParameter = filterEventsControl.ComboBoxParameters.SelectedIndex != 0 && filterEventsControl.ComboBoxParameters.SelectedItem != null;
    bool selectedStatus = filterEventsControl.ComboBoxStatus.SelectedIndex != 0 && filterEventsControl.ComboBoxStatus.SelectedItem != null;

    if (selectedModel && !selectedIp && !selectedParameter && !selectedStatus)
    {
        var model = filterEventsControl.ComboBoxModels.SelectedItem.ToString();
         if (evnt.DeviceName == model)
         {
             e.Accepted = true;
         }
         else
         {
             e.Accepted = false;
         }
     }
     else if (selectedModel && selectedIp && !selectedParameter && !selectedStatus)
     {
         var model = filterEventsControl.ComboBoxModels.SelectedItem.ToString();
         var ip = filterEventsControl.ComboBoxIPs.SelectedItem.ToString();

         if (evnt.DeviceName == model && evnt.Ip == ip)
         {
             e.Accepted = true;
         }
         else
         {
             e.Accepted = false;
         }
     } 

    ...

     else
     {
        e.Accepted = true;
     }
}
}

1 个答案:

答案 0 :(得分:0)

可能是这样的:

bool FilterByName(Event evnt)
{
  var model = filterEventsControl.ComboBoxModels.SelectedItem?.ToString();
  return evnt.DeviceName == model;
}

bool FilterByIp(Event evnt)
{
  var ip = filterEventsControl.ComboBoxIPs.SelectedItem?.ToString();
  return evnt.Ip == ip;
}

void ViewSource_Filter(object sender, FilterEventArgs e)
{
...
  bool res = true;
  if (selectedModel)
    res = res && FilterByName();
  if (selectedIp)
    res = res && FilterByIp();
...
}