2012-07-26 126 views
5

我有兩個組合框在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列出specifc汽車製造到選定item中的組合框1。

如果選擇Peurgeut然後在組合框中2應該有一個列表:

106 
206 
306 

如果選擇了寶馬然後

4 series 
5 series 

等等

+0

您可以參考[如何:使用具有分層數據的主 - 細節模式](http://msdn.microsoft.com/zh-cn/library/ms742531.aspx)。 – Gqqnbig 2012-07-26 03:36:49

回答

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

我希望這將有助於。

+0

謝謝你完美+1大家。 – 2012-07-26 03:57:45

+0

你能告訴我你的代碼和我一起工作嗎? – ethicallogics 2012-07-26 03:57:51

+0

這非常有幫助! – HoKy22 2014-03-06 21:08:53

0

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

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

SelectedText不在wpf中,選定的值或項目會給出非預期的參考比較。 – 2012-07-26 03:38:35

1

除非您查找數據,否則我認爲您只需使用XAML即可完成。但是,如果你創建了一個類綁定您的組合框,你可以有一類的東西,如:

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

然後在你的第一個組合框,只需綁定到列表的與信息的實例填充,然後將其綁定像第二個組合框:

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

這應該讓你去...