我有两个comboxbox,一个有省份列表,另一个应该填充与所选省份相对应的城市。 我的问题是,当我改变省份时,城市的combox永远不会被填满。
XML文件:
<ComboBox x:Name="ProvincesCombo" ItemsSource="{StaticResource Provinces}" IsSynchronizedWithCurrentItem="true" > </ComboBox>
<ComboBox x:Name="CitiesCombo" ItemsSource="{Binding SelectedItem.Cities, ElementName=ProvincesCombo}" IsSynchronizedWithCurrentItem="true">
</ComboBox>
代码:
ObservableCollection<Province> Provinces = new ObservableCollection<Province>();
Provinces.Add(new Province() { Name = "أدرار", Cities = new ObservableCollection<string>() { "تيط", "تيمقطن", "أقبلى", "أولف", "تبمياوين", "أوقروت", "أولاد السعيد", "تيميمون" } });
Provinces.Add(new Province() { Name = "الأغواط", Cities = new ObservableCollection<string>() { "الحاج المشري", "عين سيدي علي", "قلتة سيدي سعد", "الأغواط", "الخنق", "الحويطة" } });
DataContext = this;
public class Province
{
public string Name { get; set; }
public ObservableCollection<string> Cities { get; set; }
}
答案 0 :(得分:0)
我已将第一个组合框的ItemsSource
从StaticResource
更改为Binding
,并将字段Provinces
更改为属性,所有内容都按预期工作。
XAML:
<ComboBox x:Name="ProvincesCombo" ItemsSource="{Binding Provinces}" IsSynchronizedWithCurrentItem="true" />
<ComboBox x:Name="CitiesCombo" ItemsSource="{Binding SelectedItem.Cities, ElementName=ProvincesCombo}" IsSynchronizedWithCurrentItem="true" />
代码隐藏:
public MainWindow()
{
InitializeComponent();
DataContext = this;
Provinces.Add(new Province() { Name = "A", Cities = new ObservableCollection<string>() { "City A1", "City A2" } });
Provinces.Add(new Province() { Name = "B", Cities = new ObservableCollection<string>() { "City B1", "City B2" } });
}
public ObservableCollection<Province> Provinces { get; set; } = new ObservableCollection<Province>();
我还实现了INotifyPropertyChanged
接口。