如何在WPF中将数据集绑定到组合框

3
我想将组合框与数据集绑定,并从组合框中获取值作为参数,以填充WPF中的另一个组合框。

很好。你有什么问题? - Andrew Shepherd
太过模糊了。如果你希望别人花费精力回答问题,你需要在提问上下功夫。需要更多细节;附上一小段代码也不会有坏处。 - Charlie
1个回答

4

以下内容可以帮助您入门。在Window_Loaded事件中,设置了一个包含几行的DataTable,并设置了ComboBoxDataContextDisplayMemberPath。在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[] { "" };
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接