如何在WPF中将组合框与数据集绑定
我想用dataset绑定combo,并将combo中的值作为参数进行填充如何在WPF中将组合框与数据集绑定,wpf,data-binding,combobox,Wpf,Data Binding,Combobox,我想用dataset绑定combo,并将combo中的值作为参数进行填充 WPF中的另一个组合应该可以让您开始。加载的窗口\u事件设置一个包含两行的数据表,并设置组合框的DataContext和DisplayMemberPath。Countries\u SelectionChanged事件获取SelectedItem(如果有)并将Cities.ItemsSource属性重置为方法调用的结果,该方法调用返回一个IEnumerable。此调用可以是任何您想要的(数据库调用、文件操作等)。希望这有帮助
WPF中的另一个组合应该可以让您开始。加载的
窗口\u
事件设置一个包含两行的数据表,并设置组合框的DataContext
和DisplayMemberPath
。Countries\u SelectionChanged
事件获取SelectedItem
(如果有)并将Cities.ItemsSource
属性重置为方法调用的结果,该方法调用返回一个IEnumerable
。此调用可以是任何您想要的(数据库调用、文件操作等)。希望这有帮助
<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[] { "" };
}
已加载私有无效窗口(对象发送器、路由目标){
DataTable dt=新的DataTable();
添加(“国家”,类型(字符串));
DataRow firstRow=dt.NewRow();
DataRow secondRow=dt.NewRow();
第一行[“国家”]=“美国”;
第二行[“国家”]=“意大利”;
dt.Rows.Add(第一行);
dt.行。添加(第二行);
Countries.DisplayMemberPath=“国家”;
Countries.DataContext=dt;
}
私有无效国家/地区\u选择已更改(对象发送者,选择已更改的国家/地区){
DataRowView dr=Countries。选择EdItem作为DataRowView;
如果(dr!=null){
Cities.ItemsSource=null;
Cities.ItemsSource=GetCities(dr[“Country”].ToString());
}
}
私人IEnumerable GetCities(字符串国家){
如果(国家=“美国”)
返回纽约[]{“纽约”、“芝加哥”、“洛杉矶”、“达拉斯”、“丹佛”};
如果(国家=“意大利”)
返回新[]{“罗马”、“威尼斯”、“佛罗伦萨”、“庞贝”、“那不勒斯”};
返回新的[]{”“};
}
太好了。你的问题是什么?太模糊了。如果你想让人们为答案付出努力,你就需要为问题付出努力。需要更多的细节;代码片段也不会有什么坏处。