heyNow
heyNow

Reputation: 886

wpf nested databinding for listboxes and listitems

I'm new to WPF and databinding. I need to bind expander header to a List(Of Names) and expander content to a List(Of Services). I'm even more confused after reading MS tutorials on databindings (how and where to use staticResource, Path, etc.)

I have a

-------------
class Person 

name as string 
List servies as List (Of Services)

end class
--------------
class Service

name as string 
end class
----------------

In my main class Application.vb i have a list of Person objects

p1 as List(of Person)

I initialize all of them to dummy values. in Application.xaml, I have

<Expander Name="listBox4" VerticalAlignment="Top" 
 HorizontalAlignment="Left" Header="   {Binding}" Content="{Binding}" >

  <Expander.HeaderTemplate >

      <DataTemplate>
         <TextBlock Text="{Binding}"/>
      </DataTemplate>

   </Expander.HeaderTemplate> 

   <Expander.ContentTemplate>

      <DataTemplate >
        <ListBoxItem Content="{Binding}"/> 
      </DataTemplate>

    </Expander.ContentTemplate>                 

</Expander >

How do I bind header textblock to the person name and the inner listbox item to their services ?

Upvotes: 2

Views: 1917

Answers (1)

Rachel
Rachel

Reputation: 132618

Since you are working with a List of objects, you need to use an ItemsControl. Expanders can only deal with one DataContext, while ItemsControls were meant to work with Lists or Collections

Your code should look something like this:

<ItemsControl ItemsSource="{Binding PersonList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Expander Header="{Binding Name}">
                <ListBox ItemsSource="{Binding Services}" />
            </Expander>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

This creates a loop that says go through the PersonList and for each Person it generates an Expander with the Header equal to the Person's name and the Expanded Content equal to a ListBox which displays all of that Person's Services.

Upvotes: 3

Related Questions