CollectionViewSource 违反 MVVM

asd*_*bil 4 .net c# wpf mvvm

我有一个 MVVM 应用程序,在我的几个 VM 中,我CollectionViewSource.GetDefaultView(datasource)用来初始化我的 ICollectionView,它运行良好。我担心在我的虚拟机中使用 CVS 时我是否违反了 MVVM?

感谢大家的投入

esh*_*ham 5

我通常更喜欢在视图模型中公开一个集合并在 XAML 中创建集合视图源:

<Window.Resources>
    <CollectionViewSource x:Key="CollectionViewSource" Source="{Binding Items}">
        <i:Interaction.Behaviors>
            <behaviors:MyFilterLogic />
        </i:Interaction.Behaviors>
    </CollectionViewSource>
</Window.Resources>

<ItemsControl ItemsSource="{Binding Source={StaticResource CollectionViewSource}}" />
Run Code Online (Sandbox Code Playgroud)

和行为类:

public class MyFilterLogic: Behavior<CollectionViewSource>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.Filter += AssociatedObjectOnFilter;
    }

    private void AssociatedObjectOnFilter(object sender, FilterEventArgs filterEventArgs)
    {
        // filter logic
    }
}
Run Code Online (Sandbox Code Playgroud)

其他一些专家实际上不介意从他们的视图模型中公开 CollectionView:https : //stackoverflow.com/a/979943/3351315

  • 当然可以 - 您可以将自定义行为逻辑附加到 CollectionViewSource 对象。我已经修改了我的答案以显示过滤。 (2认同)