WPF, Listbox items as source to other Listbox

680 views Asked by At

Let's say you have one Listbox in WPF with items such as 1,2,3,4,5 etc. How do you make another Listbox, right next to first one, that shows its items according to selection in the first Listbox? So if you select "item 2" in Listbox you'd get 2A, 2B,2C etc in Listbox2, if you select "item 3" you'd get 3A, 3B, 3C etc in Listbox3

Can't embed the picture yet but here's the example of what i need

1

There are 1 answers

0
mm8 On BEST ANSWER

There is an example of how to implement such cascading ComboBoxes according to the recommended MVVM design pattern available here: https://blog.magnusmontin.net/2013/06/17/cascading-comboboxes-in-wpf-using-mvvm/

You could bind the SelectedItem property of the first ListBox to a source property of your view model. In the setter of this one you then set another collection property that you bind the ItemsSource property of the second ListBox to, e.g.:

<ListBox ItemsSource="{Binding Numbers}" SelectedItem="{Binding SelectedNumber}" />

<ListBox ItemsSource="{Binding SubNumbers}" />

private object _selectedNumber;
public object SelectedNumber
{
    get { return _selectedNumber; }
    set
    {
        _selectedNumber = value;
        NotifyPropertyChanged();

        //set items
        SubNumbers = new List<string> { "3A", "3B", "..." };
        NotifyPropertyChanged("SubNumbers");
    }
}

Make sure that your view model class implements the INotifyPropertyChanged interface and raises change notifications for this to work: https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx

Alternatively, if your model classes are defined in such a way that each item in the first ListBox has a collection property that returns its related items, you could bind the second ListBox directly to a property of the SelectedItem in the first one:

<ListBox x:Name="lb1" ItemsSource="{Binding Numbers}"/>

<ListBox x:Name="lb2" ItemsSource="{Binding SelectedItem.SubProperty, ElementName=lb1}" />