Hi,@vitaminchik. Welcome Microsoft Q&A. For the second ComboBox to display data according to the SelectedItem of the first ComboBox, you could refer to the following code.
MainWindow.xaml:
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<StackPanel Orientation="Horizontal">
<StackPanel>
<TextBlock Text="Categories" Width="100"/>
<ComboBox ItemsSource="{Binding Categories}" Width="100" Height="50" DisplayMemberPath="Name" SelectedItem="{Binding SelectedCategory}" />
</StackPanel>
<StackPanel>
<TextBlock Text="Proucts" Width="100"/>
<ComboBox ItemsSource="{Binding Proucts}" Width="100" Height="50" DisplayMemberPath="Name" SelectedItem="{Binding SelectedProduct}" />
</StackPanel>
</StackPanel>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class Category
{
public string Name { get; set; }
public ICollection<Product> Proucts { get; set; }
}
public class Product
{
public string Name { get; set; }
public Category Category { get;set; }
}
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
this.Categories = new ObservableCollection<Category>()
{ new Category(){ Name = "Vegetables", Proucts = new ObservableCollection<Product>() { new Product(){ Name = "Carrot" }, new Product(){ Name = "Tomato" }, new Product(){ Name = "Potato" } }},
new Category(){ Name = "Fruit", Proucts = new ObservableCollection<Product>() { new Product(){ Name = "Apple" }, new Product(){ Name = "Banana" }, new Product(){ Name = "Pear" } }},
new Category(){ Name = "Seafood", Proucts = new ObservableCollection<Product>() { new Product(){ Name = "Lobster" }, new Product(){ Name = "Crab" }, new Product(){ Name = "Scallop" }}}
};
this.Proucts = new ObservableCollection<Product>();
this.SelectedCategory = this.Categories[0];
}
public ObservableCollection<Category> Categories { get; private set; }
public ObservableCollection<Product> Proucts { get; private set; }
private Category _selectedCategory;
public Category SelectedCategory
{
get
{
return _selectedCategory;
}
set
{
_selectedCategory = value;
this.Proucts.Clear();
foreach (Product product in _selectedCategory.Proucts)
this.Proucts.Add(product);
}
}
public Product SelectedProduct { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it. Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.