作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将组合与数据集绑定(bind),并将组合中的值作为参数来填充WPF 中的另一个组合
最佳答案
这应该可以帮助您入门。 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[] { "" };
}
关于wpf - 如何在 WPF 中将组合框与数据集绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1303920/
我是一名优秀的程序员,十分优秀!