4

I Have an ItemsControl with a defined ItemTemplate. The ItemTemplate contains an image. The Image has a style trigger to set the image.

What binding can I use to trigger a different image to be displayed if the item is the last in the list?

Athari
  • 33,702
  • 16
  • 105
  • 146
David Ward
  • 3,739
  • 10
  • 44
  • 66

1 Answers1

3

While the simplest approach for this is still probably to add an indicator field at the VM / collection level and refer to that property in the Trigger, there are some alternatives too.

One such could be to use the AlternationCount of the ItemsControl. This approach will make sure you're last item's special style is retained when changes are made to the source collection like when adding/removing/ sorting and sorts.

  • In the ItemsControl set AlternationCount="{Binding Items.Count}" (Items is the collection being bound to)
  • As for the trigger in ItemTemplate to detect the last item, it's a bit more complicated.

xaml:

<DataTrigger Value="True">
  <DataTrigger.Binding>
    <MultiBinding Converter="{StaticResource MyConverter}">
      <Binding Path="(ItemsControl.AlternationIndex)"
                RelativeSource="{RelativeSource FindAncestor,
                                                AncestorType=ContentPresenter}" />
      <Binding Path="ItemsSource.Count"
                RelativeSource="{RelativeSource FindAncestor,
                                                AncestorType=ItemsControl}" />
    </MultiBinding>
  </DataTrigger.Binding>
  <!-- Change the following setter to what you need for new image -->
  <Setter Property="Foreground"
          Value="Tomato" />
</DataTrigger>

and the converter used:

internal class MyConverter : IMultiValueConverter {
  public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
    bool result;
    try {
      result = System.Convert.ToInt32(values[0]) == System.Convert.ToInt32(values[1]) - 1;
    } catch (Exception) {
      result = false;
    }
    return result;
  }

  public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) {
    throw new NotImplementedException();
  }
}
Viv
  • 17,170
  • 4
  • 51
  • 71