3
我想递归绑定到TreeView中的项目的子项。从我在MSDN上可以看到的HierarchicalDataTemplate是要走的路,但到目前为止,我只是部分成功。在WPF TreeView中递归绑定
我的类:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DocumentText test = new DocumentText();
this.DataContext = test;
for (int i = 1; i < 5; i++)
{
test.AddChild();
}
foreach (DocumentText t in test.Children)
{
t.AddChild();
t.AddChild();
}
}
}
partial class DocumentText
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public override string ToString()
{
return Name;
}
public List<DocumentText> _children;
public List<DocumentText> Children
{
get { return this._children; }
}
public DocumentText()
{
_name = "Test";
_children = new List<DocumentText>();
}
public void AddChild()
{
_children.Add(new DocumentText());
}
}
我的XAML: 在mainview.xaml:
<Window x:Class="treetest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TreeView Name="binderPanel" DockPanel.Dock="Left"
MinWidth="150" MaxWidth="250" Background="LightGray"
ItemsSource="{Binding Children}">
</TreeView>
</Grid>
</Window>
在App.xaml中:
<HierarchicalDataTemplate x:Key="BinderTemplate"
DataType="{x:Type src:DocumentText}" ItemsSource="{Binding Path=/Children}">
<TreeViewItem Header="{Binding}"/>
</HierarchicalDataTemplate>
这段代码产生的第一个列表孩子,但不显示嵌套的孩子。
谢谢!那就是诀窍。我也不知道HeaderTemplate。 – Clay 2010-08-18 18:50:51
我很惊讶你的解决方案有效,因为你的对象不会引发属性或集合更改的事件,并且在你填充它们的集合之前就绑定了它们。 – 2010-08-18 18:56:27
@Robert - 我认为这是因为Binding不是在构造函数完成之后才开始的,而是在InitializeComponent期间保存的。尽管需要更改通知+1。如果实现INotifyPropertyChanged并使用ObservableCollection而不是List,它将在以后节省很多挫折。 – 2010-08-18 21:40:19