Skip to main content
Home Forums General Silverlight Getting Started Simple parent-child listbox problem
2 replies. Latest Post by elmore.adam on July 4, 2009.
(0)
Todd.Net
Member
0 points
1 Posts
07-04-2009 5:15 PM |
I have a collection of objects that I have successfully bound to a listbox. Each of those objects has a collection property. When a selection is made, I want to bind ItemsSource of the child listbox to the collection property of the selected object. I know I can do this in code within the SelectionChanged event, but this seems like something I should be able to do relativley simply with some databinding syntax that eludes me to this point.
Example:
public class group { public string name { get; set; } public List<person> members { get; set; } public override string ToString() { return name; } } public class person { public string firstname { get; set; } public string lastname { get; set; } public override string ToString() { return firstname + " " + lastname; } }
<ListBox x:Name="lbGroups" ItemsSource="{Binding Path=Groups}"/> <ListBox x:Name="lbMembers" ItemsSource="???" />
Is there a way to do this with databinding? Or, do I have to use code to get this kind of behavior.
Todd
ZeroKoll
Participant
752 points
130 Posts
07-04-2009 5:49 PM |
Hey Todd!You can do this using databinding, but you will still need a little more code. Coonsidering how you are binding this, I guess you have a "parent" object that contains the list of groups. Create a SelectedGroup property on that object. Bind the SelectedItem of the ListBox to the SelectedGroup object with a TwoWay binding. Then bind ListBox two to the SelectedGroup property. Something like this...
public class MyViewModel : INotifyPropertyChanged{public Group[] Groups { get; set;}public Group SelectedGroup { get; set; } // With INotifyPropertyChanged support}
<ListBox x:Name="lbGroups" ItemsSource="{Binding Path=Groups}" SelectedItem={Binding SelectedGroup, Mode=TwoWay}/> <ListBox x:Name="lbMembers" ItemsSource="{Binding SelectedGroup.Members}" />
I know that code is not complete, but it should give you an idea...
BTW, this can be done using an element-to-element binding in SL3, but that is unfortunately not available in SL2...
// Chris
elmore.adam
482 points
67 Posts
07-04-2009 6:29 PM |
There are workarounds for element-to-element binding in Silverlight 2, but with your current scenario the solution Chris suggests is best.