How can i know if a ListBoxItem
is the last item of the collection (in the ItemContainerStyle
or in the ItemContainer
's template) inside a Wpf's ListBox
?
That question is because I need to know if an item is the last item to show it in other way. For example: suppose i want to show items separated by semi-colons but the last one: a;b;c
This is easy to do in html and ccs, using ccs selector. But, how can i do this in Wpf?
As it seems to be rather difficult to implement an "Index" attached property to ListBoxItem to do the job right, I believe the easier way to accomplish that would be in MVVM. You can add the logic necessary (a "IsLast" property, etc) to the entity type of the list and let the ViewModel deal with this, updating it when the collection is modified or replaced.
EDIT
After some attempts, I managed to implement indexing of ListBoxItems (and consequently checking for last) using a mix of attached properties and inheriting ListBox. Check it out:
To test it, we setup a simple ViewModel and an Item class:
The view:
In the view's code behind I put some logic to test the behavior of the solution when updating the collection:
This solution can handle static lists and also ObservableCollections and adding, removing, inserting items to it. Hope you find it useful.
EDIT
Tested it with CollectionViews and it works just fine.
In the first test, I changed Sort/GroupDescriptions in the ListBox.Items. When one of them was changed, the ListBox recreates the containeirs, and then PrepareContainerForItemOverride hits. As it looks for the right index in the ListBox.Items itself, the order is updated correctly.
In the second I made the Items property in the ViewModel a ListCollectionView. In this case, when the descriptions were changed, the CollectionChanged was raised and the ListBox reacted as expected.