Silverlight & WPF - Binding to a specific item in a collection

If you have a collection of items (for example a list of strings) that is assigned to the DataContext of a given XAML element (or parent element) you can use standard array index notation to get at a specific item in the list, just use Path=[n] where n is the item index.

For example:

<TextBlock Name="exampleBindingText" Text="{Binding Path=[3]}" />

With a DataContext set using the code:

            List<string> months = new List<string>()
            {
                "Jan", // 1st element in collection at index 0
                "Feb", // 2nd element in collection at index 1
                "Mar", // 3rd element in collection at index 2
                "Apr"  // 4th element in collection at index 3
            };

            exampleBindingText.DataContext = months;

Would result in the Text of the TextBlock outputting "Apr" as Path=[3] will get the 4th element in the collection.

SHARE:

Add comment

Loading