对于父 ComboBox,将 绑定SelectedItem
到模型上的属性:
<ComboBox x:Name="cbCountriesList"
DataContext="{Binding CountriesCitiesList}"
IsSynchronizedWithCurrentItem="true"
ItemSource="{Binding}"
SelectedItem={Binding Path=SomePropertyOnModel} />
WhereSomePropertyOnModel
与国家列表中的项目具有相同的类型。
对于子 ComboBox,一切都应该相同:
<ComboBox x:Name="cbCitiesList" VirtualizingStackPanel.IsVirtualizing="True"
ItemsSource="{Binding CountriesCitiesList}"
IsSynchronizedWithCurrentItem ="true"
ItemSource="{Binding}" />
旁注:您会注意到我专门将 ItemsSource 绑定添加到两个 ComboBoxes。
在模型中,每当SomePropertyOnModel
设置 时,CountriesCitiesList
根据接收到的值更新 ,即:
private string _somePropertyOnModel;
public string SomePropertyOnModel
{
get { return _somePropertyOnModel; }
set
{
_somePropertyOnModel = value;
// call NotifyPropertyChanged
UpdateCountriesCitiesList();
}
}
private void UpdateCountriesCitiesList()
{
// set CountriesCitiesList based on the
// SomePropertyOnModel value
// CountriesCitiesList should be an ObservableCollection and the values
// should be cleared and then added.
CountriesCitiesList.Clear();
CountriesCitiesList.Add( "Springfield" );
}