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>

我想知道如何将第二个组合框 2 绑定到组合框 1 中所选项目的特定汽车制造商列表。

如果选择了 Peurgeut,那么在组合框二中应该有一个列表:

106
206
306 

或者如果选择了宝马,那么

4 series
5 series

等等

4

3 回答 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; }
}

我希望这将有所帮助。

于 2012-07-26T03:44:41.320 回答
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>

那应该让你去...

于 2012-07-26T03:36:56.550 回答
0

当用户选择 ComboBox1 项目时,尝试以编程方式在 box2 中添加项目。

        if (combobox1.SelectedText == "Peurgeut")
        {
            box2.Items.Add("106");
            box2.Items.Add("206");
            box2.Items.Add("306");
        }
于 2012-07-26T03:33:37.350 回答