绑定组合框到另一个组合框在WPF
我有两个组合框在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
等等
<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大家。 – 2012-07-26 03:57:45
你能告诉我你的代码和我一起工作吗? – ethicallogics 2012-07-26 03:57:51
这非常有帮助! – HoKy22 2014-03-06 21:08:53
尝试添加的项目在box2中,当用户选择ComboBox1项目时编程。
if (combobox1.SelectedText == "Peurgeut")
{
box2.Items.Add("106");
box2.Items.Add("206");
box2.Items.Add("306");
}
SelectedText不在wpf中,选定的值或项目会给出非预期的参考比较。 – 2012-07-26 03:38:35
除非您查找数据,否则我认为您只需使用XAML即可完成。但是,如果你创建了一个类绑定您的组合框,你可以有一类的东西,如:
public class CarMake
{
public string Make {get; set;}
public List<string> Models {get; set;}
}
然后在你的第一个组合框,只需绑定到列表的与信息的实例填充,然后将其绑定像第二个组合框:
<ComboBox ItemsSource="{Binding ElementName=FirstComboBox, Path=SelectedItem.Models}" ></ComboBox>
这应该让你去...
您可以参考[如何:使用具有分层数据的主 - 细节模式](http://msdn.microsoft.com/zh-cn/library/ms742531.aspx)。 – Gqqnbig 2012-07-26 03:36:49