8

我想绑定到ObservableCollectionXAML 中的一个并在那里应用分组。原则上,这工作得很好。

<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 在这里已经给出了原因。

尽管如此,我希望应该有一种方法来获得正确的观点。我错了吗?

4

3 回答 3

6

你不能那样做吗?

var _viewSource = this.FindResource("cvs") as CollectionViewSource;

如果数据已连接,我假设将有一个更新的视图。

于 2012-06-26T15:15:50.247 回答
5

我倾向于只从 VM 公开集合视图,而不是让视图定义它:

public ICollection<Employee> Employees
{
    get { ... }
}

public ICollectionView EmployeesView
{
    get { ... }
}

这样,您的 VM 就可以完全控制向视图公开的内容。例如,它可以更改排序顺序以响应某些用户操作。

于 2012-06-15T08:01:46.687 回答
1

根据J. Lennon 的回答找到了一种方法。如果我通过我的命令传递了可以访问资源的东西,那么我可以在那里查找CollectionViewSource

在 XAML 中(CollectionViewResource如上):

<Button Command="{Binding Command}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}">Do it!</Button>

在虚拟机代码中:

private void Execute(object parm)
{
    var fe = (FrameworkElement)parm;
    var cvs = (CollectionViewSource)fe.FindResource("cvs");
    cvs.View.Refresh();
}

Execute是给RelayCommand的那个。

这将回答这个问题,但我不太喜欢它。意见?

于 2012-06-27T06:07:33.867 回答