我试图从一个类实例绑定一些数据到一个TreeView。我的代码如下:在WPF中绑定到TreeView
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Parent myClass = new Parent();
this.DataContext = myClass;
}
}
public class Parent
{
private List<string> children = new List<string>;
public string Name {get;set;}
public List<string> Children
{
get { return this.children; }
set { this.children=value; }
}
public Parent()
{
this.Name = "Test";
for (int i = 1; i <= 10; i++)
{
Children.Add(i.ToString());
}
}
}
而XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:WpfApplication1"
Title="MainWindow" Height="287" Width="525">
<StackPanel Orientation="Horizontal" VerticalAlignment="Stretch">
<TreeView Name="TreeView" ItemsSource="{Binding}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</StackPanel>
</Window>
没有在我的树视图显示出来。我究竟做错了什么?
我希望看到:
- 测试
- 1
- 2
- 3
等
更新:使名儿童属性,而不是公共领域。
已更新:添加了我期望在TreeView中看到的内容
在这种情况下,我将如何让Parent.Name显示为顶级节点? 这是我希望看到的: - 测试 --1 --2 --3 --4 等 – KrisTrip 2010-03-24 15:48:47
创建类型家长的名单,并添加MyClass的给它。然后,将datacontext设置为列表而不是对象。 – apandit 2010-03-24 15:54:11