更新时间:2023-02-05 21:14:54
如果使用自定义集合,则层次结构数据模板将起作用. 我使我的课程如下:
Hierarchial Data Templates work if you use custom collections.... I made my classes like this :
public class EntityBase :ObservableCollection<object>
{
}
public class Parent : EntityBase
{
}
public class ChildA : EntityBase // Dont make it a collection if it has noe childern to be displayed so dont inherit for EntityBase
{
//Child Properties
}
public class ChildB : EntityBase
{
//Child Properties
}
现在,当您最终将数据绑定到TreeView时,您将把ChildA
和ChildB
项作为Parent
对象的子项,即
Now when you finally bind the data to you TreeView you'll make ChildA
and ChildB
items as Child items of Parent
object i.e
public ObservableCollection<object> GetData()
{
var temp = new ObservableCollection<object>();
Parent parent = new Parent(); // Root Node
temp.Add(parent);
parent.Add(new ChildA()); // ChildA as Child1 of Parent
parent.Add(new ChildA()); // ChildA as Child2 of Parent
parent.Add(new ChildB()); // ChildB as Child3 of Parent
parent.Add(new ChildB()); // ChildB as Child4 of Parent
return temp;
}
最后,层次结构数据模板将看起来像..
Finally The Hierarchial data templates will look like..
<TreeView Name="test" Grid.Row="0" ItemsSource="{Binding Path=TreeData,Source={StaticResource ResourceKey=DataSource}}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type EntityLayer:Parent}" ItemsSource="{Binding}">
<StackPanel>
<TextBlock>Parent</TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type EntityLayer:ChildA}" ItemsSource="{Binding}">
<StackPanel>
<TextBlock Text="{Binding Path = Name}"></TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type EntityLayer:ChildB}" ItemsSource="{Binding}">
<StackPanel>
<TextBlock Text="{Binding Path = Name}"></TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>