The first thing you need to do is create a SortedDictionary<string, RoomBlockViewModel>
, whose key is the hotel name. This can be done readily like this:
Dictionary<string, List<RoomBlockViewModel>> hotelRooms = result.resultSet
.Cast<RoomBlock>()
.Select(x => new RoomBlockViewModel(x))
.GroupBy(x => x.HotelName)
.ToDictionary(x => x.Key, x => x.ToList());
Hotels.DataContext = new SortedDictionary<string, List<RoomBlockViewModel>>(hotelRooms);
This assumes that the RoomBlockViewModel
exposes a HotelName
property so that you can group by it, and that the hotel names are unique. Hotels
, in this code, is the ListBox
containing the hotels.
When you bind to a dictionary in WPF, you're really binding to an IEnumerable<KeyValuePair<TKey, TValue>>
- that is, every object in the data source has a Key
and a Value
property, which in this case are of type string
and List<RoomBlockViewModel>
.
So the list of hotels has this dictionary as its data context, and uses an ItemTemplate
to present the Key
(i.e. the hotel name). And the list of room blocks has its ItemsSource
bound to SelectedItem.Value
on the Hotels
list box - because Value
contains a List<RoomBlockViewModel>
.
<DockPanel>
<ListBox x:Name="Hotels"
Margin="5"
Background="Lavender"
DockPanel.Dock="Top"
ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Key}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ListBox Margin="5"
Background="AliceBlue"
ItemsSource="{Binding ElementName=Hotels, Path=SelectedItem.Value}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Info}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>