WPF: Binding with title and subitems
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; }
}
}
You miss out INotifyPropertyChanged.
Check this
Cascade DataTemplate
is not supported well in WPF. You need to flatten them, and reference them by key.
<Grid>
<Grid.Resources>
<DataTemplate x:Key=TopicDataTemplate>
<Expander Header="{Binding Path=TopicName}" >
<Expander.Content>
<ListBox ItemTemplate={StaticResource TopicContentDataTemplate} />
</Expander.Content>
</Expander>
</DataTemplate>
<DataTemplate x:key=TopicContentDataTemplate>
<Label
Content="{Binding Path=(ItemName)}"
Width="120px"
Height="32px"
Foreground="Black" />
</DataTemplate>
</Grid.Resources>
<ListBox
Grid.Column="0"
Name="lbTopics"
ItemsSource="{Binding}"
ItemTemplate={StaticResource TopicDataTemplate} />
</Grid>
精彩评论