12

I'm trying to use a collection that is a property of another collection to bind to a listbox. The following works fine

<ListBox ItemsSource="{Binding Path=Locations[0].Buildings}">

the problem is that I need a dynamic index and

<ListBox ItemsSource="{Binding Path=Locations[index].Buildings}">

where index is an integer in my viewmodel, does not work. Does anyone know how I can associate the index in my xaml with the property in my viewmodel?

aw04
  • 10,857
  • 10
  • 56
  • 89

2 Answers2

7

where index is an integer in my viewmodel, does not work. Does anyone know how I can associate the index in my xaml with the property in my viewmodel?

One simple option would be to just expose a CurrentLocation property within your ViewModel, which was effectively Location[index]. You could then bind to it directly.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Yes I thought of this, just curious if there was another way without having to create another property with no other purpose than for binding. May very well end up being the solution though, thank you! – aw04 Jun 03 '13 at 18:29
5

A binding within a binding is not possible, So in XAML you can't bind to "index".

a. Chris Moser's method, You can create a DependencyProperty that binds to "index" Specify a change listener on the RegisterAttached handler and do your work there.

b. Use a Converter. You can provide index as the ConverterParameter

c. Bind to a POCO property. A POCO property would need its INotifyPropertyChanged signaled by the changer

Ady
  • 104
  • 3
  • 1
    b: You cannot bind to the index: https://stackoverflow.com/questions/15309008/binding-converterparameter – Wouter Apr 05 '18 at 12:20