- 从Github下载源代码
本文演示了在WPF上具有通用lambda表达式的筛选器模式。筛选器模式与管道一起在数据驱动的应用程序中大量使用。使用C#lambda表达式,可以缩短代码并使代码通用化。
管道和过滤器模式传统上,为每个新过滤器实现过滤器模式接口。可以将通用lambda表达式用作过滤器管道的输入,而不是为每个过滤器条件实现接口。结果,将减少代码。下面是一个类图:
ConditionAggregator是一个管道类,在其中存储Condition的集合。Filter拥有ConditionAggregator或Condition对数据集合应用过滤条件。Filter调用apply函数时,将执行ICondition检查方法。ConditionAggregator有事件OnFilterChanged。在视图模型类上更改集合或条件值时将触发该事件。下一节将描述使用过滤器模式的视图模型。
使用代码 视图模型中的用法MVVM框架说明可以在此链接中阅读。在MVVM中,视图模型的职责之一是处理用户交互和数据更改。在我们的例子中,应将过滤条件值更改传递给业务层,以将过滤器应用于给定的数据集合。视图模型中的条件值更改将触发订阅了应用过滤器方法的ConditionAggregator OnFilterChanged事件。下面是视图模型的类图:
创建Employee实体类以包含employee信息。过滤器设计模式的泛型T类型将替换为Employee类。EmployeeList保存要应用的employee数据和Filters列表。类的构造函数接收条件列表并传递到过滤器列表。
public EmployeeList(IEmployeesRepository repository,
ConditionAggregator conditionAggregator)
{
this.repository = repository;
this.filters = new ConcreteFilter(conditionAggregator);
conditionAggregator.OnFilterChanged += this.FilterList;
_ = initAsync();
}
FilterList方法订阅OnFilterChanged事件,以在条件或值更改事件发生时对数据应用过滤器。
private void FilterList()
{
this.Employees = this.filters.Apply(this.employeesFullList);
}
EmployeesViewModel已连接到UI。在此示例应用程序中,仅演示了一个EmployeeTypeselected属性过滤器,但可以将许多过滤器传递给ConditionAggregator。以下代码段是一个构造函数方法,其中注册了Filter条件。
public EmployeesViewModel(IEmployeesRepository repository)
{
this.repository = repository;
Condition filterEmployee =
new Condition((e) => e.employeeCode == this.EmployeeTypeSelected);
this.conditionAggregator =
new ConditionAggregator
(new List { filterEmployee });
this.EmployeeList = new EmployeeList(repository, this.conditionAggregator);
}
条件以lambda表达式形式给出。由于ConditionAggregator构造函数可以接受List过滤条件,因此可以根据需要进行任意设置。达到了减少代码创建特定过滤条件类别的主要目的。
WPF.Demo.DataFilter项目是WPF UI视图。它有一个grid和一个combobox要过滤。WPF.Demo.DataFilter.ViewModels项目会处理资料并筛选变更,并重新载入资料以更新UI。WPF.Demo.DataFilter.Common项目是Filter和流水线模式的完整实施。WPF.Demo.DataFilter.DAL加载简单的json文件作为数据存储。
这是主界面: