将组合框与wpf中的另一个组合框结合

时间:2012-07-26 03:24:10

标签: c# html wpf binding

我在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>

我想知道你如何将第二个combobox2绑定到listcop1中的所选项目列表特定的汽车。

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

106
206
306 

或者如果选择了宝马

4 series
5 series

等等

3 个答案:

答案 0 :(得分:7)

    <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 :(得分: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>

那应该让你去......

答案 2 :(得分:0)

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

        if (combobox1.SelectedText == "Peurgeut")
        {
            box2.Items.Add("106");
            box2.Items.Add("206");
            box2.Items.Add("306");
        }