WPF:绑定标题和子项

时间:2010-05-21 02:39:45

标签: c# wpf xaml

我在尝试学习WPF时遇到了一些问题。我想要做的是绑定一个具有字符串和字符串数组的类。我想将字符串绑定为标题和数组作为扩展器的内容,但我遇到了困难。我缺少什么让这项工作?任何帮助将不胜感激,TIA。

这是我到目前为止的代码:

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; }
}
}

2 个答案:

答案 0 :(得分:0)

你错过了INotifyPropertyChanged。

检查this

答案 1 :(得分:0)

WPF中不支持级联DataTemplate。你需要弄平它们,并用钥匙引用它们。

<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>