如何获取在 XAML 中定义的集合视图
本文关键字:定义 集合 视图 XAML 何获取 获取 | 更新日期: 2023-09-27 18:37:22
我想绑定到 XAML 中的ObservableCollection
并在那里应用分组。原则上,这工作正常。
<UserControl.Resources>
<CollectionViewSource x:Key="cvs" Source="{Binding Path=TestTemplates}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Title"/>
</CollectionViewSource.SortDescriptions>
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="TestCategory"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</UserControl.Resources>
然后,数据绑定表达式变为ItemsSource="{Binding Source={StaticResource ResourceKey=cvs}}"
而不是ItemsSource="{Binding Path=TestTemplates}"
。
起初,一切看起来都很酷,直到我想从视图模型刷新 UI。问题是,CollectionViewSource.GetDefaultView(TestTemplates)
返回的视图与应用分组的 XAML 中的视图不同。因此,我无法设置选择或对其进行任何有用的操作。
我可以通过再次将列表直接绑定到视图模型的属性并在代码隐藏中设置分组来修复它。但我对这个解决方案不太满意。
private void UserControlLoaded(object sender, RoutedEventArgs e)
{
IEnumerable source = TemplateList.ItemsSource;
var cvs = (CollectionView)CollectionViewSource.GetDefaultView(source);
if (cvs != null)
{
cvs.SortDescriptions.Add(new SortDescription("Title", ListSortDirection.Ascending));
cvs.GroupDescriptions.Add(new PropertyGroupDescription("TestCategory"));
}
}
我认为,约翰·斯基特(John Skeet)在这里已经给出了原因。
尽管如此,我希望应该有一种方法来获得正确的观点。我错了吗?
我倾向于只从 VM 公开集合视图,而不是让视图定义它:
public ICollection<Employee> Employees
{
get { ... }
}
public ICollectionView EmployeesView
{
get { ... }
}
这样,VM 就可以完全控制向视图公开的内容。例如,它可以更改排序顺序以响应某些用户操作。
你不能这样做吗?
var _viewSource = this.FindResource("cvs") as CollectionViewSource;
如果数据已连接,我假设将具有更新的视图。
根据J.列侬的回答找到了一种方法。如果我使用我的命令传递可以访问资源的内容,那么我可以在那里查找CollectionViewSource
。
在 XAML 中(CollectionViewResource
如上):
<Button Command="{Binding Command}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}">Do it!</Button>
在 VM 代码中:
private void Execute(object parm)
{
var fe = (FrameworkElement)parm;
var cvs = (CollectionViewSource)fe.FindResource("cvs");
cvs.View.Refresh();
}
Execute
是提供给中继命令的那个。
这将回答这个问题,但我不太喜欢它。意见?