Populate ComboBox based on another ComboBox using XAML

痴心易碎 提交于 2019-12-12 19:07:15

问题


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?


回答1:


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!




回答2:


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:


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.



来源:https://stackoverflow.com/questions/6874376/populate-combobox-based-on-another-combobox-using-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!