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?
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?
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.
ItemsControl
set AlternationCount="{Binding Items.Count}"
(Items
is the collection being bound to)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();
}
}