更新时间:2022-10-21 16:22:04
Hi 3ib,
I do one sample about populating combobox based on another combobox using xaml, please take a look:
xaml:
<StackPanel> <ComboBox Width="300" Margin="0,20,0,20" DisplayMemberPath="Id" ItemsSource="{Binding parents}" SelectedItem="{Binding selectedparent}" /> <ComboBox Width="100" DisplayMemberPath="name" ItemsSource="{Binding childs}" SelectedItem="{Binding selectedchild}" /> </StackPanel>xaml.cs:
/// </summary> public partial class Window2 : Window { public Window2() { InitializeComponent(); this.DataContext = new viewmodel(); } } public class viewmodel:ViewModelBase { private ObservableCollection<parent> _parents; public ObservableCollection<parent> parents { get { return _parents; } set { _parents = value; RaisePropertyChanged("parents"); } } private ObservableCollection<child> _childs; public ObservableCollection<child> childs { get { return _childs; } set { _childs = value; RaisePropertyChanged("childs"); } } private parent _selectedparent; public parent selectedparent { get { return _selectedparent; } set { _selectedparent = value; RaisePropertyChanged("selectedparent"); childs = _selectedparent.childs; RaisePropertyChanged("childs"); } } private child _selectedchild; public child selectedchild { get { return _selectedchild; } set { _selectedchild = value; RaisePropertyChanged("selectedchild"); } } public viewmodel() { parents = new ObservableCollection<parent>() { new parent(){Id=1,FirstChar="a", childs=new ObservableCollection<child>() { new child(){Id=1,name="a1"}, new child(){Id=2,name="a2"}, new child(){Id=3,name="a3"}, new child(){Id=4,name="a4"}, } }, new parent(){Id=2,FirstChar="b", childs=new ObservableCollection<child>() { new child(){Id=1,name="b1"}, new child(){Id=2,name="b2"}, new child(){Id=3,name="b3"}, new child(){Id=4,name="b4"}, } }, new parent(){Id=3,FirstChar="c", childs=new ObservableCollection<child>() { new child(){Id=1,name="c1"}, new child(){Id=2,name="c2"}, new child(){Id=3,name="c3"}, new child(){Id=4,name="c4"}, } } }; selectedparent = parents[0]; } } public class parent { public Int32 Id { get; set; } public string FirstChar { get; set; } public ObservableCollection<child> childs { get; set; } } public class child { public Int32 Id { get; set; } public string name { get; set; } }
Here is also a sample, you can take a look:
Best Regards,
Cherry