Here's a complete example of two dependent ComboBoxes in WPF, where selecting an item in the first ComboBox updates the items displayed in the second ComboBox.
Step-by-Step Explanation
Create a WPF Project: Start a new WPF application in Visual Studio.
ViewModel Setup: Implement a ViewModel with INotifyPropertyChanged to handle data binding and property updates.
Dependent Logic: Use a dictionary to map the relationship between the first ComboBox (e.g., categories) and the second ComboBox (e.g., items).
XAML UI: Bind the ComboBoxes to the ViewModel properties and handle selection changes.
ViewModel Code
csharp
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class ViewModel : INotifyPropertyChanged
{
private Dictionary<string, List<string>> _itemMap;
private List<string> _mainItems;
private List<string> _subItems;
private string _selectedMainItem;
public List<string> MainItems
{
get => _mainItems;
set
{
_mainItems = value;
OnPropertyChanged();
}
}
public List<string> SubItems
{
get => _subItems;
set
{
_subItems = value;
OnPropertyChanged();
}
}
public string SelectedMainItem
{
get => _selectedMainItem;
set
{
_selectedMainItem = value;
OnPropertyChanged();
UpdateSubItems();
}
}
public ViewModel()
{
_itemMap = new Dictionary<string, List<string>>()
{
{ "Fruits", new List<string> { "Apple", "Banana" } },
{ "Vegetables", new List<string> { "Carrot", "Broccoli" } }
};
MainItems = new List<string>(_itemMap.Keys);
SelectedMainItem = MainItems.FirstOrDefault();
}
private void UpdateSubItems()
{
if (_itemMap.TryGetValue(SelectedMainItem, out var items))
{
SubItems = items;
}
else
{
SubItems = new List<string>();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}