筛选ICollectionView后如何选择第一项

时间:2018-11-22 12:29:58

标签: c# wpf listview icollectionview

我在我的视图模型中将ListView绑定到ICollectionView。 ICollectionView具有一些预定义的筛选器,单击某些按钮时将应用它们。但是,我似乎找不到任何方法来(自动)筛选出集合后在ListView中选择第一个项目。

我尝试将SelectedIndex设置为0,将Target和Source通知都添加到绑定中,但是当应用过滤器时,所有通知均无效。

任何有关如何实现这一目标的指针?

编辑:下面的代码说明了我要说的问题。

XAML:

<Window x:Class="CollectionViewTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CollectionViewTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Window.DataContext>
        <local:MainViewModel/>
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>

        <!-- MENU -->
        <StackPanel Orientation="Vertical">
            <Button Content="Numbers below 4" Click="Below4_Click" Width="100"/>
            <Button Content="Numbers below 7" Click="Below7_Click" Width="100"/>
            <Button Content="All numbers" Click="All_Click" Width="100"/>
        </StackPanel>

        <!-- LIST -->
        <ListView 
            Grid.Column="1" 
            SelectedIndex="0"
            ItemsSource="{Binding Numbers, Mode=OneWay}"
            SelectedItem="{Binding SelectedNumber, Mode=TwoWay}">
            <ListView.Resources>
                <DataTemplate DataType="{x:Type local:Number}">
                    <TextBlock Text="{Binding Value}" />
                </DataTemplate>
            </ListView.Resources>
        </ListView>

        <!-- DETAILS -->
        <TextBlock Grid.Column="2" Text="{Binding SelectedNumber.Text}" Width="100"/>
    </Grid>
</Window>

隐藏代码:

using System.Windows;

namespace CollectionViewTest
{
    public partial class MainWindow : Window
    {
        private MainViewModel vm;
        public MainWindow()
        {
            InitializeComponent();
            vm = (MainViewModel)DataContext;
        }

        private void Below4_Click(object sender, RoutedEventArgs e)
        {
            vm.MenuFilter = f => f.Value < 4;
        }

        private void Below7_Click(object sender, RoutedEventArgs e)
        {
            vm.MenuFilter = f => f.Value < 7;
        }

        private void All_Click(object sender, RoutedEventArgs e)
        {
            vm.MenuFilter = f => true;
        }
    }
}

ViewModel:

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Data;
using System.Collections.ObjectModel;

namespace CollectionViewTest
{
    public class MainViewModel : PropertyChangedBase
    {

        public MainViewModel()
        {
            Numbers = new ObservableCollection<Number>();
            NumberCollection = CollectionViewSource.GetDefaultView(Numbers);
            NumberCollection.Filter = Filter;
            NumberCollection.SortDescriptions.Add(new SortDescription("Value", ListSortDirection.Ascending));

            for (int i = 0; i < 10; i++)
                Numbers.Add(new Number { Value = i, Text = $"This is number {i}." });

        }

        private Func<Number, bool> menuFilter;
        public Func<Number, bool> MenuFilter
        {
            get => menuFilter;
            set
            {
                menuFilter = value;
                NumberCollection.Refresh();
            }
        }

        private bool Filter(object item)
        {
            var number = (Number)item;
            return MenuFilter == null ? true : MenuFilter(number);
        }

        public ObservableCollection<Number> Numbers { get; set; }
        public ICollectionView NumberCollection { get; set; }

        private Number selectedNumber;
        public Number SelectedNumber { get => selectedNumber; set => Set(ref selectedNumber, value); }
    }

    public class Number : PropertyChangedBase
    {
        public int Value { get; set; }

        private string text;
        public string Text { get => text; set => Set(ref text, value); }
    }

    public class PropertyChangedBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void Set<T>(ref T field, T newValue = default(T), [CallerMemberName] string propertyName = null)
        {
            field = newValue;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

如您所见,按下按钮之一将更改“过滤器”并在集合上调用“刷新”。我想拥有的是,列表中的第一项(此处为“ 0”)是自动选择的,然后将在第2列的文本中显示文本“ This is number 0”。

我已经尝试了SelectedIndex = 0和MoveCurrentToFirst,但是什么也没选择。

1 个答案:

答案 0 :(得分:3)

绑定到SelectedIndex时不要设置ICollectionView。而是通过MoveCurrentTo()MoveCurrentToFirst()设置其CurrentItem

myCollectionView.MoveCurrentTo(someItem);
...
myCollectionView.MoveCurrentToFirst();

还要在ListView上设置IsSynchronizedWithCurrentItem

<ListView IsSynchronizedWithCurrentItem="True" ...

应用过滤器时检测

在评估过滤器时,将刷新集合视图,从而重置集合。要检测到此情况,请监听CollectionChanged事件并寻找NotifyCollectionChangedAction.Reset标志。有关更多详细信息,请参见CollectionView source code