14
<TextBlock Text="{Binding Path=[0]} />

or

<TextBlock Text="{Binding Path=[myKey]} />

works fine. But is there a way to pass a variable as indexer key?

<TextBlock Text="{Binding Path=[{Binding Column.Index}]} />
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
Marinko Babic
  • 151
  • 1
  • 4

3 Answers3

13

The quickest way to handle this is usually to use a MultiBinding with an IMultiValueConverter that accepts the collection and the index for its bindings:

<TextBlock.Text>
    <MultiBinding Converter="{StaticResource ListIndexToValueConverter}">
        <Binding /> <!-- assuming the collection is the DataContext -->
        <Binding Path="Column.Index"/>
    </MultiBinding>
</TextBlock.Text>

The converter can then do the lookup based on the two values like this:

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    if (values.Length < 2)
        return Binding.DoNothing;

    IList list = values[0] as IList;
    if (list == null || values[1] == null || !(values[1] is int))
        return Binding.DoNothing;

    return list[(int)values[1]];
}
John Bowen
  • 24,213
  • 4
  • 58
  • 56
0

This calls for a IValueConverter IMultiValueConverter.

decyclone
  • 30,394
  • 6
  • 63
  • 80
-1

No, I'm afraid not. At this point you should probably consider creating a view model that shapes your data to make it easier to bind to it.

ColinE
  • 68,894
  • 15
  • 164
  • 232