Binding to the First Element of a Collection
Yes! It's another in a long series of posts that fall under the category of, "things many people already knew but I just discovered"!
Today I had a form with an ObjectDataProvider that retrieved a collection of objects. However, I didn't want to display the entire collection. See, in 99% of cases I knew that this collection would only contain one item; and in the other 1% of cases I knew that the user wouldn't care. So all I ever wanted to do was display the first item in the collection.
So I had dropped a ContentPresenter on the form, and set its content to my ObjectDataProvider. But now when the form displayed it simply showed the text "(Collection)". This was obviously not what I wanted.
So how then do you bind to just the first element of a collection? My first instinct was to write an IValueConverter, which I did, and that worked well. However, I've just discovered an easier way.
It turns out that Binding.Path supports indexers into collections! You can actually say this on your ContentPresenter:
<ContentPresenter Content="{Binding Source={StaticResource MyObjectDataProvider},Path=[0]}"/>
How cool is that? That binds to the first element of the collection provided by "MyObjectDataProvider"! Works a treat! Another insight into the power that is WPF.
Comments
# aca
28/01/2012 5:25 PM
would you give an example? im trying to do this but stressed out without succeed
# Richard
29/10/2016 12:47 AM
Where I have a List<MyObject> and MyObject has a property List<Something> is it possible to use this syntax to access a property of Something for the first Something in the List for that MyObject?
I've tried a few variations without success.
<Label Text="{Binding Somethings.Propertry, Path=[0]"/>