How to get the first element of a CollectionViewSource?

北战南征 提交于 2019-12-06 14:27:45

问题


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.



来源:https://stackoverflow.com/questions/11110425/how-to-get-the-first-element-of-a-collectionviewsource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!