I have a listbox and it’s bound to a list of simple objects. As we know the listbox by default has it’s items host as a Stackpanel and so it lays out items in this fashion
item1
item2
item3
item4
item5
item6
However i have some conditions through which i check whether the item is to be displayed horizontally or vertically and therefore the items could be laid out in this fashion
Eg :-
item1
item2
item3 item4 item 5
item6
How is it possible to do this?
(If you are wondering why would i ever need such a thing, an example scenario would be “facebook style updates” where if a user uploads 3-4 photos continously they don’t always appear on the next line but it may appear horizontally whereas if he posts some event it appears in next line.)
Thanks in advance 🙂
The fundementals of the solution is to use another
ItemsControlin theItemTemplateof theListBox. ThisItemsControlshould have a horizontal orientedStackPanelas itsItemsPanel.Here is a basic example. Lets start with some very simple testdata:-
Now we want to display this list in a ListBox but keep all the names that have the same first initial on the same line. I’m going to use an implementation of
IValueConverterto deal with the grouping that we need. If you are using MVVM then you’d have your ViewModel take of this.The output of this converter is basically
IEnumerable<IEnumerable<string>>which is what we want. The outer ListBox will enumerate the outer set and the innerItemsControlwill enumerate the inner set of strings which will be a set of names with the same initial.Here is the xaml:-