簡體   English   中英

將組合框與wpf中的另一個組合框結合

[英]binding combobox to another combobox in wpf

我在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以列出特定於carobox1中所選項目的carc。

如果Peurgeut被選中,那么在組合框2中應該有一個列表:

106
206
306 

或者如果選擇了寶馬那么

4 series
5 series

等等

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

我希望這將有所幫助。

除非您查看數據,否則我認為您不能僅使用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>

這應該讓你去...

當用戶選擇ComboBox1項時,嘗試以編程方式添加box2中的項目。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM