效果如图
数据结构
public class DisplayViewModel
{
public string Name { get; set; }
public List<DisplayViewModel> Children { get; set; }
}
前端TreeView通过ItemTemplate
为其子级设置样式
<TreeView x:Name="treeView">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<StackPanel>
<TextBlock VerticalAlignment="Center" FontSize="18" Text="{Binding Name}" Margin="2,0,0,0"></TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
设置数据源
List<DisplayViewModel> vm = new List<DisplayViewModel>();
DisplayViewModel oneData = new DisplayViewModel() { Name="1", Children=new List<DisplayViewModel>()};
oneData.Children.Add(new DisplayViewModel() { Name = "1-1", Children = new List<DisplayViewModel>()
{
new DisplayViewModel(){Name="1-1-1",Children=new List<DisplayViewModel>()}
}
});
oneData.Children.Add(new DisplayViewModel()
{
Name = "1-2",
Children = new List<DisplayViewModel>()
{
new DisplayViewModel(){Name="1-2-1",Children=new List<DisplayViewModel>()
{
new DisplayViewModel(){Name="1-2-1-2",Children=new List<DisplayViewModel>()}
}
}
}
});
vm.Add(oneData);
vm.Add(new DisplayViewModel() { Name = "2", Children = new List<DisplayViewModel>() });
treeView.ItemsSource = vm;