我想将组合框与数据集绑定,并从组合框中获取值作为参数,以填充WPF中的另一个组合框。
以下内容可以帮助您入门。在Window_Loaded
事件中,设置了一个包含几行的DataTable,并设置了ComboBox
的DataContext
和DisplayMemberPath
。在Countries_SelectionChanged
事件中,获取了所选项(如果有),并将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[] { "" };
}