Search code examples
c#wpfdata-bindingdatatemplateitemspaneltemplate

Data binding to a collection with different behavior for the last element


This seems like it would be a common issue, but my Google-Fu left me empty-ended. Apologies if this has been asked a thousand times before!

I have a collection, say an ObservableCollection<Athlete>. I want to display that collection on screen so that it looks something like:

[Jersey Pic] | [Jersey Pic] | [Jersey Pic] | [Jersey Pic]

The key in this contrived example is the little bar, between each picture. Subtract that bar and it's just a ListBox bound to the collection, with a ItemsPanelTemplate of a horizontal StackPanel, and then an ItemTemplate to show the corresponding jersey picture for each item. No problems!

The question is then, how to append the bar, which could be any graphical element, after all but the last element in the collection?

Thank you!


Solution

  • As suggested in the link from @KornMuffin, you can put the bar in the left side of ListBox item :

    | [Jersey Pic] | [Jersey Pic] | [Jersey Pic] | [Jersey Pic]

    Then use DataTrigger with {RelativeSource PreviousData} binding, to hide the first bar if previous data is null. For example, assume that I'm using Separator to display the bar, I can add this style to the separator control to hide the first separator :

    <Separator.Style>
        <Style TargetType="Separator">
            <Style.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource PreviousData}}" Value="{x:Null}">
                    <Setter Property="Visibility" Value="Collapsed"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Separator.Style>