根据另一个ComboBox选择更改ComboBox ItemsSource

时间:2017-03-27 15:27:56

标签: c# wpf combobox binding

我有两个ComboBoxes A和B.第一个填充了一个项目列表。 我需要根据A ItemsSource

更改B的Binding SelectedItem

问题:在A上选择X时,B未填充。

请注意,我过滤ItemsSource,这是对绑定的完全更改。 myItemSources是ObservableCollections

 <ComboBox Name="ComboBoxB">
    <ComboBox.Style>
      <Style TargetType="{x:Type ComboBox}">
           <Setter Property="ItemsSource" Value="{Binding myItemSource1}" />
              <Style.Triggers>
                <DataTrigger Binding="{Binding SelectedValue, ElementName=ComboBoxA}" Value="X">
                  <Setter Property="ItemsSource" Value="{Binding myItemSource2}" />
                </DataTrigger>
          </Style.Triggers>
      </Style>
    </ComboBox.Style>
</ComboBox>

1 个答案:

答案 0 :(得分:2)

有一个示例说明如何使用此处提供的MVVM设计模式实现此类级联ComboBox:https://blog.magnusmontin.net/2013/06/17/cascading-comboboxes-in-wpf-using-mvvm/

<ComboBox ItemsSource="{Binding Countries}"
          DisplayMemberPath="Name"
          SelectedItem="{Binding SelectedCountry}" />

<ComboBox ItemsSource="{Binding Cities}"
          DisplayMemberPath="Name"
          SelectedItem="{Binding SelectedCity}"
          Margin="0 5 0 0"/>
public CustomObservableCollection<City> Cities {
  get;
  private set;
}

private Country _selectedCountry;
public Country SelectedCountry {
  get {
    return _selectedCountry;
  }
  set {
    _selectedCountry = value;
    this.Cities.Repopulate(_selectedCountry.Cities);
  }
}
...
}