Search code examples
wpfdata-binding

WPF Master/Detail data binding between 2 combobox


I have two combobox where Parent has to show the list of Countries and the child combo has to show a list of cities of the choosen country. The data is stored in a Dictionary<Int32, List<String>> which has the name CountriesCitiesList. I have the following code

<ComboBox x:Name="cbCountriesList" 
    DataContext="{Binding CountriesCitiesList}"
    IsSynchronizedWithCurrentItem="true">
</ComboBox>

<ComboBox x:Name="cbCitiesList" VirtualizingStackPanel.IsVirtualizing="True"                  
          ItemsSource="{Binding CountriesCitiesList}"
          IsSynchronizedWithCurrentItem="true">
</ComboBox>

The issue is that in the cities combo i can't show the cities list of the country selected. It feel to me that is missing a final step.


Solution

  • If your dictionary CountriesCitiesList contains country Id as Key and List as cities name, you can bind it in pure xaml way something like this -

    <ComboBox x:Name="cbCountriesList"
              ItemsSource="{Binding CountriesCitiesList}"
              IsSynchronizedWithCurrentItem="True">
       <ComboBox.ItemTemplate>
          <DataTemplate>
             <TextBlock Text="{Binding Key}"/>
          </DataTemplate>
       </ComboBox.ItemTemplate>
    </ComboBox>
    <ComboBox x:Name="cbCitiesList"
              ItemsSource="{Binding SelectedItem.Value, ElementName=cbCountriesList}"
              IsSynchronizedWithCurrentItem="True"/>
    

    I am assuming you want to show country Id's in cbCountriesList since you are binding it to the dictionary with key of int type.