In my program I have a comboBox
and a listBox
. The listBox
is full of different commands. The selectedItem
and contents of the comboBox
depend on which command is selected. The selectedItem
in the comboBox
stays selected for that command. For example, when the user has content selected in the comboBox
and they switch to a different command, and then switch back, the same item will still be selected in the comboBox
.
Because the comboBox
gets populated with different items depending on which command is selected should I make an ObservableCollection
for each set of items? I'm only allowed to bind the ItemsSource
to one thing, so how would that work?
If that's not the right approach please advise. If this isn't clear enough, please let me know.
Thanks!
Here's a sample of what my program will look like:
Then, if command 2 is selected, the list in the combo box might be a, b, c, d, e, for example.
You can have a separate ObservableCollection for each listbox command.
When the user selects a new listbox command, set the comboBox.ItemsSource to the appropriate ObservableCollection. That should solve your problem.
Based on your description, the contents of the combobox
are tied to the selected item in the listbox
. Without knowing any more of the details, seems like your business object would be a “Command” object that contains an ObservableCollection
of “SubCommand”? objects. Your application would then contain an Observablecollection
of “Command” objects. The listbox
would be data bound to the "Command" objects list, and the combobox
would be bound to the selected items "SubCommand" collection.
Seems to me you're looking for a Master / Detail structure here:
Data Items:
public class MyCommandDefinition
{
public string DisplayName {get;set;}
public List<MyParameter> Parameters {get;set;}
public Parameter SelectedParameter {get;set;}
}
public class MyParameter
{
public string DisplayName {get;set;}
//Additional properties depending on your needs.
}
ViewModel:
public class MyViewModel
{
public List<MyCommandDefinition> Commands {get;set;}
public MyCommandDefinition SelectedCommand {get;set;}
}
XAML:
<ListBox ItemsSource="{Binding Commands"}"
SelectedItem="{Binding SelectedCommand}"
DisplayMemberPath="DisplayName"/>
<ComboBox ItemsSource="{Binding SelectedCommand.Parameters}"
SelectedItem="{Binding SelectedCommand.SelectedParameter}"
DisplayMemberPath="DisplayName"/>
Don't forget NotifyPropertyChanged()
in all these properties if you're going to change them programatically and expect that to be reflected in the UI.