我可以绑定到集合视图的第一项吗?

本文关键字:一项 绑定 集合 视图 我可以 | 更新日期: 2023-09-27 18:32:36

我正在将ListBox绑定到ViewModel(从现在开始的VM)上定义的ICollectionView。我有一个选定项 ( SelectedFoo ) 的属性,该属性设置为 VM 构造函数中的第一个。

当有人在文本框中输入文本时,我会根据该输入过滤集合(到目前为止,一切顺利)。

在应用某些筛选后,如何将所选索引设置为集合中的第一项?我无法从代码绑定到ICollectionView中的第一个对象。

有什么想法吗?

下面是一些精简的代码,包括List、我在 XAML 中绑定到的ICollectionView,以及筛选的代码位于FooFilterString中,该代码在用户键入文本框时会更新。

// This is the underlying list
public List<Foo> FooList
{
    get { return _fooList; }
    set
    {
        if (Equals(value, _fooList)) return;
        _fooList = value;
        RaisePropertyChanged();
    }
}
private  List<Foo> _fooList;

// This is what the list box binds to
public ICollectionView FooListView
{
    get { return _fooListView; }
    set
    {
        if (Equals(value, _fooListView)) return;
        _fooListView = value;
        RaisePropertyChanged();
    }
}
private ICollectionView _fooListView ;

// This is bound to from the XAML, as user types, it will filter the list.
// I want to bind to the first item of the filtered list.
public string FooFilterString
{
    get { return _fooFilterString; }
    set
    {
        _fooFilterString = value;
        FooListView.Filter = (s => some_logic); // <-- filters the list
        /*
         * How can I set the selected index here ?!
         */
    }
}
private string _fooFilterString;
// I Bind to this, and want to set this after filtering. First time, I just 
// set it to the first item from the FooList, but after filtering, I'm loosing
// the selection
public Foo SelectedFoo { 
    get { /*...*/ }
    set { /*...*/ }
}
private Foo _selectedFoo;

我可以绑定到集合视图的第一项吗?

要汇总注释以从ICollectionView中选择第一项,您可以使用ICollectionView.MoveCurrentToFirst()

FooListView.Filter = s => some_logic;
FooListView.MoveCurrentToFirst() 

您还需要启用IsSynchronizedWithCurrentItem

<ListBox ... IsSynchronizedWithCurrentItem="True">