使用Caliburn Micro和MVVM时如何实现ListView按Status属性分组
解决方案
你可以通过以下两种符合MVVM规范的方案实现分组,无需访问视图控件,也不用写后置代码事件。
方案1:纯XAML实现(推荐,视图层逻辑完全和业务层分离)
直接在XAML中通过CollectionViewSource定义分组规则,无需修改现有ViewModel逻辑:
- 在当前页面/窗体的资源区声明CollectionViewSource,绑定你的搜索结果集合,指定分组属性:
<Window.Resources> <CollectionViewSource x:Key="GroupedSearchResults" Source="{Binding SearchResults}"> <CollectionViewSource.GroupDescriptions> <PropertyGroupDescription PropertyName="Status" /> </CollectionViewSource.GroupDescriptions> </CollectionViewSource> </Window.Resources>
- 修改ListView的ItemsSource绑定到这个资源即可,你原有写好的GroupStyle、GridView代码完全不用改动:
<ListView DockPanel.Dock="Top" ItemsSource="{Binding Source={StaticResource GroupedSearchResults}}"> <!-- 原有GridView、GroupStyle代码保持不变 -->
方案2:ViewModel中实现分组(适合分组规则需要和业务逻辑联动的场景)
直接在ViewModel中操作集合的默认视图,不用接触任何UI控件:
修改DoSearch方法,在搜索结果赋值后添加分组规则:
public async void DoSearch() { List<Claim> results = await AugmentorCore.Search.SearchTelephones(SearchString); SearchResults = new BindableCollection<Claim>(results); // 操作集合的默认视图添加分组,和具体UI控件无关,完全符合MVVM规范 var collectionView = CollectionViewSource.GetDefaultView(SearchResults); collectionView.GroupDescriptions.Clear(); collectionView.GroupDescriptions.Add(new PropertyGroupDescription("Status")); }
注意:
PropertyGroupDescription的属性名要和Claim类中实际的Status属性大小写完全一致,避免绑定失效。
内容的提问来源于stack exchange,提问作者Eurisko
相关产品推荐
相关产品推荐

