在WPF中将一个ComboBox绑定到另一个ComboBox

8

我在WPF中有两个组合框,其中一个组合框如下所示:

            <ComboBox Height="23" HorizontalAlignment="Left" Margin="244,10,0,0" Name="comboBox2" VerticalAlignment="Top" Width="120">
                <ComboBoxItem Content="Peugeut" />
                <ComboBoxItem Content="Ford" />
                <ComboBoxItem Content="BMW" />
            </ComboBox>

我想知道如何将第二个下拉框与第一个下拉框中选择的特定汽车品牌列表绑定。如果选择了Peugeot,则在第二个下拉框中应该有一个列表:
106
206
306 

如果选择了宝马,则执行以下操作。
4 series
5 series

And so on


3个回答

9
    <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50"/>
        <RowDefinition Height="50"/>
    </Grid.RowDefinitions>

    <ComboBox Height="23" ItemsSource="{Binding Cars}" DisplayMemberPath="Name" HorizontalAlignment="Left" Margin="244,10,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120"/>
    <ComboBox Height="23" Grid.Row="1" ItemsSource="{Binding SelectedItem.Series, ElementName=comboBox1}" HorizontalAlignment="Left" Margin="244,10,0,0" Name="comboBox2" VerticalAlignment="Top" Width="120"/>

</Grid>

    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Cars = new ObservableCollection<Car>();
        Cars.Add(new Car() { Name = "Peugeut", Series = new ObservableCollection<string>() { "106", "206", "306" } });
        Cars.Add(new Car() { Name = "Ford", Series = new ObservableCollection<string>() { "406", "506", "606" } });
        Cars.Add(new Car() { Name = "BMW", Series = new ObservableCollection<string>() { "706", "806", "906" } });
        DataContext = this;

    }

    public ObservableCollection<Car> Cars { get; set; }

}
public class Car
{
    public string Name { get; set; }
    public ObservableCollection<string> Series { get; set; }
}

希望这能有所帮助。


1

除非你查找数据,否则我认为你不能仅使用XAML完成它。但是,如果你创建一个类来绑定你的组合框,你可以拥有一个类似以下代码的类:

public class CarMake
{
    public string Make {get; set;}
    public List<string> Models {get; set;}
}

然后在您的第一个组合框中,只需绑定到填充了信息的List实例,然后像这样绑定第二个组合框:

<ComboBox ItemsSource="{Binding ElementName=FirstComboBox, Path=SelectedItem.Models}" ></ComboBox>

那应该能帮助你开始了......


0
尝试在用户选择ComboBox1项目时以编程方式添加箱子2中的项目。
        if (combobox1.SelectedText == "Peurgeut")
        {
            box2.Items.Add("106");
            box2.Items.Add("206");
            box2.Items.Add("306");
        }

SelectedText不在WPF中,而选定的值或项会导致意外的引用比较。 - G Gr

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