Search code examples
c#wpfxamlcomboboxcompositecollection

Binding a set of lists to a combobox from another list of objects which contain the lists


For simplicity sake, I am going to use the idea of a "car make" and a "car model" to explain my problem. I have a list of car make objects and each car make has its own list of car models. I need to populate a combo box which contains a list of all car models. I have researched this and believe that a CompositeCollection is the way to go, however, I can't seem to figure out how to do this when I don't know how large my CarMake list will be. With a fixed-length CarMake list I can do the following but I need it to be dynamic.

<ComboBox x:Name="carSelectComboBox" DisplayMemberPath="Name">
    <ComboBox.Resources>
        <CollectionViewSource x:Key="CarMake0Collection" 
                              Source="{Binding CarMakes[0].Models}"  />
        <CollectionViewSource x:Key="CarMake1Collection" 
                              Source="{Binding CarMakes[1].Models}" />
    </ComboBox.Resources>
    <ComboBox.ItemsSource>
         <CompositeCollection>
             <CollectionContainer Collection="{Binding Source={StaticResource CarMake0Collection}}" />
             <CollectionContainer Collection="{Binding Source={StaticResource CarMake1Collection}}" />
         </CompositeCollection>
     </ComboBox.ItemsSource>
 </ComboBox>

Any help would be much appreciated. Also, there is a chance (even a likelihood) that the list of car makes, as well as the car models, may grow/change while running the application.


Solution

  • This sounds like a problem for converter, unless you have good reason not to.

    public class CarMakeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, 
            object parameter, CultureInfo culture)
        {
            var input = (List<CarMakes>)value;
            return input.SelectMany(carMake=> carMake.Models);
        }
    
        public object ConvertBack(object value, Type targetType, 
            object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
    

    And later being used in your ComboBox:

    <ComboBox x:Name="carSelectComboBox"
     ItemsSource="{Binding CarMakes, Converter={StaticResource converter}"
     DisplayMemberPath="Name"/>