简体   繁体   中英

Can I bind to the first item of a CollectionView?

I'm binding a ListBox to an ICollectionView defined on the ViewModel (VM from now). I have a property for the selected item ( SelectedFoo ) that is set to be the first in the VM constructor.

When someone enters text in a textbox, I filter the collection based on that input (so far, so good).

How can I set the selected index to be the first item in the collection after some filtering was applied? I can't bind to the first object in the ICollectionView from the code.

Any ideas?

Here's some stripped down code, including the List , the ICollectionView that I bind to in the XAML, and the code that filters is in the FooFilterString which is updated as the user types into the text box.

// 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;

To sum up comments to select first item from ICollectionView you can use ICollectionView.MoveCurrentToFirst()

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

you'll also need to enable IsSynchronizedWithCurrentItem

<ListBox ... IsSynchronizedWithCurrentItem="True">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM