How to get the first element of a CollectionViewSo

2020-07-28 11:12发布

问题:

I remember seen some code xaml where can get the first element (like an index x[0]) from a collection.

This is my CollectionViewSource from Resources.

<CollectionViewSource
            x:Name="groupedItemsViewSource2"
            Source="{Binding Posters}"
            ItemsPath="Posters" />

If I display this in a listbox, it loaded it!

<ListBox ItemsSource="{Binding Source={StaticResource groupedItemsViewSource2}}" />

But right now, I just want to get the first element through xaml. Is it possible doing this?

回答1:

I faced similar issue, and what i did was to call MoveCurrentToFirst (in ViewModel)

`SelectedIndex=0 (on ListBox in XAML), was another way but it was failing when Collection view source does not hold any data.



回答2:

The easiest way I have found so far is to go via enumerator:

ICollectionView view = CollectionViewSource.GetDefaultView(observable);
var enumerator = view.GetEnumerator();
enumerator.MoveNext(); // sets it to the first element
var firstElement = enumerator.Current;

or you can do the same with an extension and call it directly on the observable collection:

public static class Extensions
{
    public static T First<T>(this ObservableCollection<T> observableCollection)
    {
        ICollectionView view = CollectionViewSource.GetDefaultView(observableCollection);
        var enumerator = view.GetEnumerator();
        enumerator.MoveNext();
        T firstElement = (T)enumerator.Current;
        return firstElement;
    }
}

and then call it from the observable collection:

var firstItem = observable.First();


回答3:

There are a couple ways of accomplishing this that I know of. I'd probably go with either a separate property that returns the first of the collection, or create a Converter that will return the first element in any collection or list it is bound to.