WPF: Binding with title and subitems
- by John
I am having some issues trying to learn WPF. What I am trying to do is to bind a class that has a string and an array of strings. I would like to bind the string as the title and array as the contents of an expander, but I am having difficulties. What am I missing to make this work? Any help would be appreciated, TIA.
This is the code I have thus far:
XAML
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<ListBox Grid.Column="0" Name="lbTopics" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<Expander Header="{Binding Path=TopicName}" >
<Expander.Content>
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Path=(ItemName)}" Width="120px" Height="32px" Foreground="Black" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Expander.Content>
</Expander>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
C#
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
lbTopics.DataContext = new Topics();
}
}
public class Topics : ObservableCollection<Topic>
{
public Topics()
{
for (int i = 0; i < 10; i++)
{
this.Add(new Topic(i));
}
}
}
public class Topic
{
public Topic(int i)
{
TopicName = "Topic " + i;
ItemName = new List<string>(10);
for (int j = 0; j < 10; j++)
{
ItemName.Add(i + " - Item " + j);
}
}
public string TopicName { get; set; }
public List<string> ItemName { get; set; }
}
}