如何浏览ICollectionView

本文关键字:ICollectionView 浏览 何浏览 | 更新日期: 2023-09-27 18:31:14

所以我有一个基本的视图模型,其功能如下:

// The ICollectionVIew is what my ListBox binds to.
public ICollectionView UserView { get; set; }
// <signup> is a model that's populated from a database representing a signup table
private ObservableCollection<signup> _signup;
    public ObservableCollection<signup> Signup
    {
        get
        {
            return _signup;
        }
        set
        {
            if (_signup != value)
            {
                value = _signup;
            }
            OnPropertyChanged("Signup");
        }
    }
    // This is the constructor for the ViewModel
    public registrationVM()
    {
        // entity context Fills up the Model 
        context.signups.Load();
        // The below code fills up the ObservableCollection
        var query = context.signups;
        _signup = new ObservableCollection<signup>(query);
        // And the below code fills up the ICollectionView using the ObservableCollection
        UserView = CollectionViewSource.GetDefaultView(_signup);
    }

因此,现在我可以绑定到 ICollection,而不是绑定到 ObservableCollection。

<ListBox ItemsSource="{Binding UserView}" DisplayMemberPath="firstName" SelectedItem="{Binding SelectedUser}"/>

这在加载我的信息方面非常有效。但是现在出现了导航的问题。我将我的按钮命令绑定到视图模型,

<Button x:Name="next" Command="{Binding Next}"/>

在它的执行方法中:

    private object Next_CommandExecute(object param)
    {
        // 'UserView' Is the ICollectionView I declared earlier
        return UserView.MoveCurrentToNext();
    }

问题是按钮的功能不执行任何操作。"上一个"按钮也是如此。屏幕上选择的记录没有改变,所以我猜我做错了什么。究竟是什么我一直未能弄清楚。有人看到我哪里出错了吗?

如何浏览ICollectionView

正如我在评论中提到的,您需要在ListBox上设置IsSynchronizedWithCurrentItem = true

ListBox ItemsSource="{Binding UserView}" 
        DisplayMemberPath="firstName"
        IsSynchronizedWithCurrentItem = true 
        SelectedItem="{Binding SelectedUser}"/>