在Silverlight中使用HierarchicalDataTemplate为TreeView实现递归树状结构

在Silverlight中使用HierarchicalDataTemplate为TreeView实现递归树状结构,第1张

概述这是项目中一个页面上的一个功能。我们需要在界面上通过一个TreeView控件显示一个递归树状结构,也就是说会很多层嵌套的节点,而且层数是不确定的。 这个功能,可以通过HierarchicalDataTemplate来很方便地实现 1. 业务实体 作为举例,我定义了一个大家都很熟悉的Folder类型,即文件夹。我们都知道,文件夹又可以包含子文件夹,而且可以多层嵌套。所以,这是一个递归的结构体。

这是项目中一个页面上的一个功能。我们需要在界面上通过一个TreeVIEw控件显示一个递归的树状结构,也就是说会很多层嵌套的节点,而且层数是不确定的。

这个功能,可以通过HIErarchicalDataTemplate来很方便地实现

1. 业务实体

作为举例,我定义了一个大家都很熟悉的Folder类型,即文件夹。我们都知道,文件夹又可以包含子文件夹,而且可以多层嵌套。所以,这是一个递归的结构体。

    public class Folder    {        public string name { get; set; }        public ObservableCollection       Folders { get; set; }    }  
2. 准备数据

我用下面的代码,模拟一个数据读取 *** 作。下面是硬编码出来的数据。实际情况下,可以读取数据库。

        voID MainPage_Loaded(object sender,RoutedEventArgs e)        {            var result = new[]{                new Folder(){name="Test",Folders =new ObservableCollection      (                        new[]{                            new Folder(){name=    "Test4"},new Folder(){name=    "Test3"},new Folder(){name=    "Test4",Folders=    new ObservableCollection        (    new []{    new Folder(){name =    "Test5"}}) } })}}; tvFolders.ItemsSource = result; }   
3. 绑定控件
<UserControl x:Class="SilverlightTreevIEwSample.MainPage"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:d="http://schemas.microsoft.com/Expression/blend/2008"    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    mc:Ignorable="d"    d:DesignHeight="300" d:DesignWIDth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">        <UserControl.Resources>        <sdk:HIErarchicalDataTemplate x:Key="FolderItemTemplate" ItemsSource="{Binding Folders}">            <TextBlock Text="{Binding name}">    TextBlock>            sdk:HIErarchicalDataTemplate> <Style targettype="sdk:TreeVIEwItem"> <Setter Property="IsExpanded" Value="True">     Setter>       Style>        UserControl.Resources> <GrID x:name="LayoutRoot" Background="White"> <sdk:TreeVIEw name="tvFolders" ItemTemplate="{StaticResource FolderItemTemplate}">         sdk:TreeVIEw>          GrID>           UserControl> 

请注意,我们这里用到一个特殊的DataTemplate:HIErarchicalDataTemplate,并且将其设置为TreevIEw的ItemTemplate。

 

4. 查看效果

总结

以上是内存溢出为你收集整理的在Silverlight中使用HierarchicalDataTemplate为TreeView实现递归树状结构全部内容,希望文章能够帮你解决在Silverlight中使用HierarchicalDataTemplate为TreeView实现递归树状结构所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1077254.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存