gpt4 book ai didi

wpf - 如何在 WPF 中将组合框与数据集绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 14:17:38 25 4
gpt4 key购买 nike

我想将组合与数据集绑定(bind),并将组合中的值作为参数来填充WPF 中的另一个组合

最佳答案

这应该可以帮助您入门。 Window_Loaded事件设置一个包含几行的 DataTable,并设置 DataContextDisplayMemberPathComboBox . 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com