Thursday, September 13, 2012

How to get the first element of a CollectionViewSource?

How to get the first element of a CollectionViewSource?

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?

Answers & Comments...

Answer: 1

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.

by : McAdenhttp://stackoverflow.com/users/101197

Answer: 2

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.

by : Tilakhttp://stackoverflow.com/users/649524

Answer: 3

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

ICollectionView view = CollectionViewSource.GetDefaultView(observable); var enumerator = collectionView.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(); 
by : tridy.nethttp://stackoverflow.com/users/1374435




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog