Это должно помочь вам начать. Событие Window_Loaded
устанавливает DataTable с двумя строками и устанавливает DataContext
и DisplayMemberPath
для ComboBox
. Событие Countries_SelectionChanged
захватывает SelectedItem
(если есть) и сбрасывает свойство Cities.ItemsSource
в качестве результата вызова метода, который возвращает IEnumerable<string>
. Этот вызов может быть любым, что вы хотите (вызов базы данных, файловая операция и т. Д.). Надеюсь, это поможет!
<UniformGrid Rows="2" Columns="2">
<Label Content="Countries" VerticalAlignment="Center"/>
<ComboBox Name="Countries" VerticalAlignment="Center" SelectionChanged="Countries_SelectionChanged" ItemsSource="{Binding}"/>
<Label Content="Cities" VerticalAlignment="Center"/>
<ComboBox Name="Cities" VerticalAlignment="Center"/>
</UniformGrid>
private void Window_Loaded(object sender, RoutedEventArgs e) {
DataTable dt = new DataTable();
dt.Columns.Add("Country", typeof(string));
DataRow firstRow = dt.NewRow();
DataRow secondRow = dt.NewRow();
firstRow["Country"] = "USA";
secondRow["Country"] = "Italy";
dt.Rows.Add(firstRow);
dt.Rows.Add(secondRow);
Countries.DisplayMemberPath = "Country";
Countries.DataContext = dt;
}
private void Countries_SelectionChanged(object sender, SelectionChangedEventArgs e) {
DataRowView dr = Countries.SelectedItem as DataRowView;
if (dr != null) {
Cities.ItemsSource = null;
Cities.ItemsSource = GetCities(dr["Country"].ToString());
}
}
private IEnumerable<string> GetCities(string country) {
if (country == "USA")
return new []{ "New York", "Chicago", "Los Angeles", "Dallas", "Denver" };
if (country == "Italy")
return new[] { "Rome", "Venice", "Florence", "Pompeii", "Naples" };
return new[] { "" };
}