在 CollectionViewSource 上触发过滤器 [英] Trigger Filter on CollectionViewSource

查看:18
本文介绍了在 CollectionViewSource 上触发过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MVVM 模式开发 WPF 桌面应用程序.

I am working on a WPF desktop application using the MVVM pattern.

我正在尝试根据 TextBox 中键入的文本从 ListView 中过滤一些项目.我希望在更改文本时过滤 ListView 项目.

I am trying to filter some items out of a ListView based on the text typed in a TextBox. I want the ListView items to be filtered as I change the text.

我想知道如何在过滤器文本更改时触发过滤器.

ListView 绑定到 CollectionViewSource,后者绑定到我的 ViewModel 上的 ObservableCollection.过滤器文本的 TextBox 绑定到 ViewModel 上的字符串,UpdateSourceTrigger=PropertyChanged 应该是这样.

The ListView binds to a CollectionViewSource, which binds to the ObservableCollection on my ViewModel. The TextBox for the filter text binds to a string on the ViewModel, with UpdateSourceTrigger=PropertyChanged, as it should be.

<CollectionViewSource x:Key="ProjectsCollection"
                      Source="{Binding Path=AllProjects}"
                      Filter="CollectionViewSource_Filter" />

<TextBox Text="{Binding Path=FilterText, UpdateSourceTrigger=PropertyChanged}" />

<ListView DataContext="{StaticResource ProjectsCollection}"
          ItemsSource="{Binding}" />

Filter="CollectionViewSource_Filter" 链接到后面代码中的事件处理程序,它只是调用 ViewModel 上的过滤器方法.

The Filter="CollectionViewSource_Filter" links to an event handler in the code behind, which simply calls a filter method on the ViewModel.

过滤在 FilterText 的值发生变化时完成 - FilterText 属性的设置器调用一个 FilterList 方法,该方法迭代我的 ViewModel 中的 ObservableCollection 并设置一个 boolean FilteredOut每个项目 ViewModel 的属性.

Filtering is done when the value of FilterText changes - the setter for the FilterText property calls a FilterList method that iterates over the ObservableCollection in my ViewModel and sets a boolean FilteredOut property on each item ViewModel.

我知道 FilteredOut 属性会在过滤器文本更改时更新,但列表不会刷新.CollectionViewSource 过滤器事件仅在我通过切换和返回来重新加载 UserControl 时触发.

I know the FilteredOut property is updated when the filter text changes, but the List does not refresh. The CollectionViewSource filter event is only fired when I reload the UserControl by switching away from it and back again.

我尝试在更新过滤器信息后调用 OnPropertyChanged("AllProjects"),但它没有解决我的问题.(AllProjects"是我的 ViewModel 上的 ObservableCollection 属性,CollectionViewSource 绑定到该属性.)

I've tried calling OnPropertyChanged("AllProjects") after updating the filter info, but it did not solve my problem. ("AllProjects" is the ObservableCollection property on my ViewModel to which the CollectionViewSource binds.)

当 FilterText TextBox 的值发生变化时,如何让 CollectionViewSource 重新过滤自身?

How can I get the CollectionViewSource to refilter itself when the value of the FilterText TextBox changes?

非常感谢

推荐答案

不要在您的视图中创建 CollectionViewSource.相反,在您的视图模型中创建一个 ICollectionView 类型的属性并将 ListView.ItemsSource 绑定到它.

Don't create a CollectionViewSource in your view. Instead, create a property of type ICollectionView in your view model and bind ListView.ItemsSource to it.

完成此操作后,您可以将逻辑放入 FilterText 属性的 setter 中,该设置器在 ICollectionView 上调用 Refresh()用户更改它.

Once you've done this, you can put logic in the FilterText property's setter that calls Refresh() on the ICollectionView whenever the user changes it.

你会发现这也简化了排序的问题:你可以将排序逻辑构建到视图模型中,然后暴露视图可以使用的命令.

You'll find that this also simplifies the problem of sorting: you can build the sorting logic into the view model and then expose commands that the view can use.

编辑

这是使用 MVVM 对集合视图进行动态排序和过滤的非常简单的演示.这个演示没有实现 FilterText,但是一旦你理解了它是如何工作的,你应该不会有任何困难实现一个 FilterText 属性和一个使用该属性的谓词它现在使用的硬编码过滤器.

Here's a pretty straightforward demo of dynamic sorting and filtering of a collection view using MVVM. This demo doesn't implement FilterText, but once you understand how it all works, you shouldn't have any difficulty implementing a FilterText property and a predicate that uses that property instead of the hard-coded filter that it's using now.

(还要注意这里的视图模型类没有实现属性更改通知.这只是为了保持代码简单:因为这个演示中没有实际更改属性值,它不需要属性更改通知.)

(Note also that the view model classes here don't implement property-change notification. That's just to keep the code simple: as nothing in this demo actually changes property values, it doesn't need property-change notification.)

首先为您的物品设置一个类:

First a class for your items:

public class ItemViewModel
{
    public string Name { get; set; }
    public int Age { get; set; }
}

现在,应用程序的视图模型.这里发生了三件事:首先,它创建并填充自己的 ICollectionView;其次,它公开了一个 ApplicationCommand(见下文),视图将使用它来执行排序和过滤命令,最后,它实现了一个对视图进行排序或过滤的 Execute 方法:

Now, a view model for the application. There are three things going on here: first, it creates and populates its own ICollectionView; second, it exposes an ApplicationCommand (see below) that the view will use to execute sorting and filtering commands, and finally, it implements an Execute method that sorts or filters the view:

public class ApplicationViewModel
{
    public ApplicationViewModel()
    {
        Items.Add(new ItemViewModel { Name = "John", Age = 18} );
        Items.Add(new ItemViewModel { Name = "Mary", Age = 30} );
        Items.Add(new ItemViewModel { Name = "Richard", Age = 28 } );
        Items.Add(new ItemViewModel { Name = "Elizabeth", Age = 45 });
        Items.Add(new ItemViewModel { Name = "Patrick", Age = 6 });
        Items.Add(new ItemViewModel { Name = "Philip", Age = 11 });

        ItemsView = CollectionViewSource.GetDefaultView(Items);
    }

    public ApplicationCommand ApplicationCommand
    {
        get { return new ApplicationCommand(this); }
    }

    private ObservableCollection<ItemViewModel> Items = 
                                     new ObservableCollection<ItemViewModel>();

    public ICollectionView ItemsView { get; set; }

    public void ExecuteCommand(string command)
    {
        ListCollectionView list = (ListCollectionView) ItemsView;
        switch (command)
        {
            case "SortByName":
                list.CustomSort = new ItemSorter("Name") ;
                return;
            case "SortByAge":
                list.CustomSort = new ItemSorter("Age");
                return;
            case "ApplyFilter":
                list.Filter = new Predicate<object>(x => 
                                                  ((ItemViewModel)x).Age > 21);
                return;
            case "RemoveFilter":
                list.Filter = null;
                return;
            default:
                return;
        }
    }
}

排序很糟糕;你需要实现一个 IComparer:

Sorting kind of sucks; you need to implement an IComparer:

public class ItemSorter : IComparer
{
    private string PropertyName { get; set; }

    public ItemSorter(string propertyName)
    {
        PropertyName = propertyName;    
    }
    public int Compare(object x, object y)
    {
        ItemViewModel ix = (ItemViewModel) x;
        ItemViewModel iy = (ItemViewModel) y;

        switch(PropertyName)
        {
            case "Name":
                return string.Compare(ix.Name, iy.Name);
            case "Age":
                if (ix.Age > iy.Age) return 1;
                if (iy.Age > ix.Age) return -1;
                return 0;
            default:
                throw new InvalidOperationException("Cannot sort by " + 
                                                     PropertyName);
        }
    }
}

为了触发视图模型中的 Execute 方法,这使用了一个 ApplicationCommand 类,它是 ICommand 的一个简单实现,它路由CommandParameter 在视图中的按钮到视图模型的 Execute 方法.我以这种方式实现它是因为我不想在应用程序视图模型中创建一堆 RelayCommand 属性,并且我想将所有排序/过滤保留在一个方法中,以便于看看它是如何完成的.

To trigger the Execute method in the view model, this uses an ApplicationCommand class, which is a simple implementation of ICommand that routes the CommandParameter on buttons in the view to the view model's Execute method. I implemented it this way because I didn't want to create a bunch of RelayCommand properties in the application view model, and I wanted to keep all the sorting/filtering in one method so that it was easy to see how it's done.

public class ApplicationCommand : ICommand
{
    private ApplicationViewModel _ApplicationViewModel;

    public ApplicationCommand(ApplicationViewModel avm)
    {
        _ApplicationViewModel = avm;
    }

    public void Execute(object parameter)
    {
        _ApplicationViewModel.ExecuteCommand(parameter.ToString());
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;
}

最后,这是应用程序的MainWindow:

Finally, here's the MainWindow for the application:

<Window x:Class="CollectionViewDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:CollectionViewDemo="clr-namespace:CollectionViewDemo" 
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <CollectionViewDemo:ApplicationViewModel />
    </Window.DataContext>
    <DockPanel>
        <ListView ItemsSource="{Binding ItemsView}">
            <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Name}"
                                    Header="Name" />
                    <GridViewColumn DisplayMemberBinding="{Binding Age}" 
                                    Header="Age"/>
                </GridView>
            </ListView.View>
        </ListView>
        <StackPanel DockPanel.Dock="Right">
            <Button Command="{Binding ApplicationCommand}" 
                    CommandParameter="SortByName">Sort by name</Button>
            <Button Command="{Binding ApplicationCommand}" 
                    CommandParameter="SortByAge">Sort by age</Button>
            <Button Command="{Binding ApplicationCommand}"
                    CommandParameter="ApplyFilter">Apply filter</Button>
            <Button Command="{Binding ApplicationCommand}"
                    CommandParameter="RemoveFilter">Remove filter</Button>
        </StackPanel>
    </DockPanel>
</Window>

这篇关于在 CollectionViewSource 上触发过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆