Skip to main content

Microsoft Silverlight

Answered Question Simple parent-child listbox problemRSS Feed

(0)

Todd.Net
Todd.Net

Member

Member

0 points

1 Posts

Simple parent-child listbox problem

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
ZeroKoll

Participant

Participant

752 points

130 Posts

Answered Question

Re: Simple parent-child listbox problem

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
elmore.adam

Member

Member

482 points

67 Posts

Re: Simple parent-child listbox problem

There are workarounds for element-to-element binding in Silverlight 2, but with your current scenario the solution Chris suggests is best.

--
Kind Regards

Adam Elmore
MCTS: WPF, WCF

417.200.4261
elmore.adam@gmail.com
http://adamelmore.net/
  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities