2
votes

I have two ComboBoxes

<ComboBox Name="cmbMake" DisplayMemberPath="MakeName" SelectedValuePath="MakeID"/>
<ComboBox Name="cmbModel" DisplayMemberPath="ModelName"/>

I use LINQ-to-Entities to populate the cmbGroup ComboBox

Dim db as myDataEntity
cmbGroup.ItemsSource = db.Makes

How do I populate my second ComboBox (cmbModels) based on the selection of the first ComboBox (cmbMake) using XAML so that whatever I select in the first ComboBox automatically filters the ItemsSource in the second ComboBox?

Is this even possible?

3

3 Answers

5
votes

I am posting the full solution here

XAML

<ComboBox Name="cmbMake" DisplayMemberPath="MakeName" SelectedValuePath="MakeID"  Width="200"/>
<ComboBox Name="cmbModel" DisplayMemberPath="ModelName" DataContext="{Binding SelectedItem, ElementName=cmbMake}" Width="200"/>

CODE-BEHIND

Private Sub cmbMake_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles cmbMake.SelectionChanged

        Dim myItem = From m In myModel
                     Where m.MakeID = cmbMake.SelectedValue

        cmbModel.ItemsSource = myItem

End Sub

Whenever the value is changed in the cmbModel ComboBox it will use LINQ to reset the ItemsSource of the cmbModel ComboBox.

Many Thanks to @XAMeLi for the helping hand!

4
votes

If your data is hierarchical, where each item in db.Makes holds a list of the Models (and lets say this list is in a property called MyModelsList), then:

<ComboBox Name="cmbMake" DisplayMemberPath="MakeName" SelectedValuePath="MakeID"/>
<ComboBox Name="cmbModel" DisplayMemberPath="ModelName" DataContext="{Binding SelectedItem, ElementName=cmbMake}" ItemsSource="{Binding MyModelsList}"/>
3
votes

It should be possible to use a converter to filter the items, for that you can employ a MultiBinding to get the values for the items and the selection in the other box in.

Would look something like this:

<ComboBox Name="cmbModel" DisplayMemberPath="ModelName">
    <ComboBox.ItemsSource>
        <MutliBinding>
           <MultiBinding.Converter>
               <vc:MyFilterConverter/>
           </MultiBinding.Converter>
           <Binding Path="Items"/> <!-- This should bind to your complete items-list -->
           <Binding Path="SelectedValue" ElementName="cmbMake"/>
        </MutliBinding>
    </ComboBox.ItemsSource>
</ComboBox>

The converter needs to implement IMultiValueConverter.