WPF TrreView 递归绑定数据源

效果如图

数据结构

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;

示例代码

示例代码

参考资料

WPF下递归生成树形数据绑定到TreeView上

posted @ 2020-10-28 18:42  Lulus  阅读(469)  评论(0编辑  收藏  举报