【发布时间】:2020-06-06 07:33:29
【问题描述】:
场景很简单,但我坚持细节:
我有一个数据网格,它绑定到我的 viewModel 中的一个可观察集合。我想用三个组合框的条目过滤我的数据网格。这里还有其他关于多个过滤器的帖子,但我找不到适合我的案例或 MVVM 的帖子。在我的研究过程中,我遇到过几次让 ControlViewSource 安静下来的方法。为简单起见,我在文本后添加了一张图片。这是我的代码: MainWindow.xaml
<Window.DataContext>
<viewModels: MainViewModel />
</Window.DataContext>
<Window.Resources>
<CollectionViewSource x:Key=“CVS“ Source=“{Binding FirstFilter}“/>
</Window.Resources>
<StackPanel>
<StackPanel Orientation=“Horizontal“>
<ComboBox x:Name=“ItemsFilter“ ItemsSource=“{Binding ItemsList}“ SelectedItem="{Binding CurrentItem}"/>
<ComboBox x:Name=“ElementsFilter“ ItemsSource=“{Binding ElementsList}“ SelectedItem="{Binding CurrentElement}"/>
<ComboBox x:Name=“ValuesFilter“ ItemsSource=“{Binding ValuesList}“ SelectedItem="{Binding CurrentValue}"/>
</StackPanel>
<DataGrid x:Name=“MainGrid“ ItemsSource=“{Binding DataList}“/>
</StackPanel>
我的目标是根据每个组合框中的选定项过滤数据网格中的数据。为了给你一个想法,让我们把它简单化:
comboBox “ItemsFilter” 具有条目 “AllItems”、“ItemsA” 和 “ItemsB”(而 A 和 B 指的是像“西瓜”和“苹果”这样的项目类别,因此所有是“所有水果”)。
comboBox „ElementsFilter“还决定了“ItemsFilter”的选择:它应该有类似“AllElements”、“ElementA”、“ElementB”的东西(而这可以指品牌,比如“西瓜”( ITemsFilter) 和“品牌 A” (ElementsFilter)。
组合框“ValuesFilter”将是“AllValues”、“ValueA”、“ValueB”,并且可以是价格。
所以,直到现在,我只有一个过滤器可以工作。我的 viewModel 中的代码:
public ObservableCollection<DataItem> DataList {get; set;} = new ObservableCollection<DataItem>();
public ObservableCollection<DataItem> FirstFilter {get; set;} = new ObservableCollection<DataItem>();
private ICollectionView _myFilterView;
public ICollectionView MyFilterView
{
get {return _myFilterView;}
set
{
_myFilterView = value;
OnPropertyChange(nameof(MyFilterView);
}
}
private string _currentItem;
public string CurrentItem
{
get { return _currentItem}
set
{
_currentItem = value;
OnPropertyChange(nameofMyFilterView);
}
}
// I also have properties CurrentElement, CurrentValue --> all of them representing the currently selected item, element or value (as string) in one of the associated comboBoxes.
public MainViewModel()
{
//… loading data into my collections
MyFilterView = CollectionViewSource.GetDefaultView(FirstFilter);
MyFilterView.Filter = new Predicate<object>(ItemsFilter);
}
要完成这项工作,要做的最后一件事是在我的 viewModel 中安装将处理过滤器事件的方法:
private bool ItemsFilter(object o)
{
if(string.IsNullOrWhitespace(CurrentFilter)
{
return true;
}
else
{
if(CurrentFilter == „All Items“)
{
return true;
}
else
{
DataItem d = new DataItem();
return (d.Item == o.Item);
}
}
}
基本上——运行一个过滤器就是这样。 如何实现其他过滤器? 到目前为止我尝试了什么:
- 分配另一个 ICollectionView(不起作用 - 数据网格始终为空,即使 DefaultView 设置为同一个集合)
- 尝试在单独的方法中设置 MyFilterView.Filter,每次都设置。这个“有点”行得通,只要我的列表不是建立在分层结构上:代码变得一团糟,对于每个新的组合框,我必须编写大量嵌套的 if 语句,将它们委托给下一个检查点。 有人可以向我解释实现这一目标的简单方法吗?代码示例将非常受欢迎! 非常感谢!
【问题讨论】:
标签: wpf filter combobox datagrid