How to get the first element of a CollectionViewSource?

a 夏天 提交于 2019-12-04 19:59:42

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.

tridy.net

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();

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.

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