binding combobox to another combobox in wpf

无人久伴 提交于 2019-12-13 11:46:59

问题


I have two combo boxes in wpf one of the combo boxes looks like so:

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

I was wondering how you bind the second combobox2 to list specifc car makes to the selected item in combobox1.

If Peurgeut is selected then in combobox two there should be a list:

106
206
306 

or if bmw is selected then

4 series
5 series

And so on


回答1:


    <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; }
}

I hope this will help.




回答2:


Unless you look up the data I don't think you can do it with just XAML. If, however, you created a class to bind your combo boxes you could have a class with something like:

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

Then in your first combo box, just bind to an instance of List with the info populated, then bind the second combo box like:

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

That should get you going...




回答3:


Try to add the items in box2 programmtically when ComboBox1 item is selected by user.

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


来源:https://stackoverflow.com/questions/11661894/binding-combobox-to-another-combobox-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!