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에서 는 :
은 app.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>
는 :
<HierarchicalDataTemplate x:Key="BinderTemplate"
DataType="{x:Type src:DocumentText}" ItemsSource="{Binding Path=/Children}">
<TreeViewItem Header="{Binding}"/>
</HierarchicalDataTemplate>
이 코드는 최초의 목록을 생성 그러나 중첩 된 자식은 표시되지 않습니다.
고마워요! 그것은 트릭을했다. 나는 HeaderTemplate에 대해서도 몰랐다. – Clay
개체가 속성 또는 컬렉션 변경 이벤트를 발생시키지 않고 컬렉션에 채우기 전에 바인딩 한 것이므로 솔루션이 작동하는 것이 놀랍습니다. –
@ 로버트 - 바인딩은 InitializeComponent가 아니라 생성자가 완료 될 때까지 시작되지 않는다는 사실로 인해 저장되고 있다고 생각합니다. 변경 알림의 필요성에 +1. INotifyPropertyChanged를 구현하고 List 대신 ObservableCollection을 사용하면 나중에 많은 좌절감을 줄일 수 있습니다. –