<!-- MainWindow.xaml -->
<Window x:Class="DependentComboBoxes.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DependentComboBoxes"
mc:Ignorable="d"
Title="Dependent ComboBoxes" Height="200" Width="400">
<StackPanel Margin="10">
<Label Content="Category:"/>
<ComboBox x:Name="CategoryComboBox"
ItemsSource="{Binding Categories}"
SelectedItem="{Binding SelectedCategory}"
DisplayMemberPath="Name"
Margin="0,0,0,10"
SelectionChanged="CategoryComboBox_SelectionChanged"/>
<Label Content="Subcategory:"/>
<ComboBox x:Name="SubcategoryComboBox"
ItemsSource="{Binding Subcategories}"
DisplayMemberPath="Name"
Margin="0,0,0,10"
IsEnabled="{Binding IsCategorySelected}"/>
</StackPanel>
</Window>
// MainWindow.xaml.cs
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
namespace DependentComboBoxes
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
private Category _selectedCategory;
private ObservableCollection<Subcategory> _subcategories = new ObservableCollection<Subcategory>();
public MainWindow()
{
InitializeComponent();
DataContext = this;
// Initialize Categories
Categories = new ObservableCollection<Category>
{
new Category { Id = 1, Name = "Electronics" },
new Category { Id = 2, Name = "Clothing" },
new Category { Id = 3, Name = "Books" }
};
// Initialize Subcategories (ideally, this would come from a database or service)
AllSubcategories = new List<Subcategory>
{
new Subcategory { Id = 1, CategoryId = 1, Name = "TVs" },
new Subcategory { Id = 2, CategoryId = 1, Name = "Laptops" },
new Subcategory { Id = 3, CategoryId = 1, Name = "Smartphones" },
new Subcategory { Id = 4, CategoryId = 2, Name = "Shirts" },
new Subcategory { Id = 5, CategoryId = 2, Name = "Pants" },
new Subcategory { Id = 6, CategoryId = 2, Name = "Shoes" },
new Subcategory { Id = 7, CategoryId = 3, Name = "Fiction" },
new Subcategory { Id = 8, CategoryId = 3, Name = "Non-Fiction" },
new Subcategory { Id = 9, CategoryId = 3, Name = "Textbooks" }
};
}
public ObservableCollection<Category> Categories { get; set; }
public List<Subcategory> AllSubcategories { get; set; }
public ObservableCollection<Subcategory> Subcategories
{
get { return _subcategories; }
set
{
_subcategories = value;
OnPropertyChanged();
}
}
public Category SelectedCategory
{
get { return _selectedCategory; }
set
{
_selectedCategory = value;
OnPropertyChanged();
UpdateSubcategories();
OnPropertyChanged(nameof(IsCategorySelected)); // Notify that IsCategorySelected has changed
}
}
public bool IsCategorySelected
{
get { return SelectedCategory != null; }
}
private void UpdateSubcategories()
{
if (SelectedCategory != null)
{
Subcategories = new ObservableCollection<Subcategory>(AllSubcategories.FindAll(s => s.CategoryId == SelectedCategory.Id));
}
else
{
Subcategories = new ObservableCollection<Subcategory>(); // Clear subcategories if no category is selected
}
}
private void CategoryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//This is redundant. SelectionChanged will also call the SelectedCategory setter.
//UpdateSubcategories();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
// Simple Category Class
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
// Simple Subcategory Class
public class Subcategory
{
public int Id { get; set; }
public int CategoryId { get; set; }
public string Name { get; set; }
}
}
Explanation:
-
XAML (MainWindow.xaml):
-
CategoryComboBox: This is the first combo box.
ItemsSource="{Binding Categories}": Binds the combo box's items to the Categories property in the view model.
SelectedItem="{Binding SelectedCategory}": Binds the selected item to the SelectedCategory property in the view model.
DisplayMemberPath="Name": Specifies that the Name property of the Category object should be displayed in the combo box.
SelectionChanged="CategoryComboBox_SelectionChanged": This is wired up to the CategoryComboBox_SelectionChanged event handler in the code-behind, which, when you select something different, triggers the subcategory update. This is actually redundant in this specific implementation.
-
SubcategoryComboBox: This is the second, dependent combo box.
ItemsSource="{Binding Subcategories}": Binds the combo box's items to the Subcategories property in the view model.
DisplayMemberPath="Name": Specifies that the Name property of the Subcategory object should be displayed in the combo box.
IsEnabled="{Binding IsCategorySelected}": This is important. It disables the SubcategoryComboBox until a category is selected. This prevents errors or unexpected behavior.
-
C# (MainWindow.xaml.cs):
-
Data Classes (Category, Subcategory): These are simple classes to hold the category and subcategory data. They have properties for Id, Name, and, in the case of Subcategory, CategoryId to relate it to a category.
-
View Model (MainWindow class):
Categories: An ObservableCollection<Category> that holds the list of categories. ObservableCollection is important because it automatically notifies the UI when its contents change.
AllSubcategories: A List<Subcategory> holding all the possible subcategories. In a real-world application, this would likely come from a database or a service.
How it Works:
- Initialization: The
MainWindow constructor creates sample Category and Subcategory data. The Categories property is populated, which populates the CategoryComboBox. AllSubcategories are also populated and ready.
- Category Selection: When the user selects a category in the
CategoryComboBox, the SelectedCategory property in the view model is updated.
- Dependency Update: The
set accessor of the SelectedCategory property triggers the UpdateSubcategories() method. This method filters the AllSubcategories list, selecting only the subcategories that belong to the selected category, and populates the Subcategories collection. Because Subcategories is an ObservableCollection, the SubcategoryComboBox automatically updates to display the new list of subcategories.
- Enabling/Disabling Subcategory ComboBox: The
IsCategorySelected property controls the IsEnabled state of the SubcategoryComboBox. It ensures that the user can only select a subcategory after a category has been selected.
Key Concepts:
- Data Binding: WPF's data binding mechanism allows you to connect UI elements (like combo boxes) directly to properties in your code (view model).
INotifyPropertyChanged: This interface is essential for data binding. It allows your view model to notify the UI when its properties change.
ObservableCollection<T>: This collection class automatically notifies the UI when items are added, removed, or replaced. This is ideal for populating combo boxes, lists, and other data-bound controls.
- Dependency: The
SubcategoryComboBox is dependent on the CategoryComboBox because its contents are dynamically updated based on the selection in the CategoryComboBox.
To Run this Example:
- Create a new WPF project in Visual Studio.
- Replace the contents of
MainWindow.xaml and MainWindow.xaml.cs with the code provided above.
- Build and run the project.
You should see two combo boxes. Initially, the "Subcategory" combo box will be disabled. When you select a category from the "Category" combo box, the "Subcategory" combo box will be enabled and will display the subcategories associated with the selected category.