开发者

Populate ComboBox based on another ComboBox using XAML

开发者 https://www.devze.com 2023-03-23 16:07 出处:网络
I have two ComboBoxes <ComboBox Name=\"cmbMake\" DisplayMemberPath=\"MakeName\" SelectedValuePath=\"MakeID\"/>

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?


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!


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}"/>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消