treeview控件使用详解

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了treeview控件使用详解相关的知识,希望对你有一定的参考价值。

参考技术A TreeView 控件的主要属性包括 Nodes 和 SelectedNode。Nodes 属性包含树视图中的顶级节点列表。SelectedNode 属性设置当前选中的节点。您可以在节点旁边显示图标。该控件使用在树视图的 ImageList 属性中命名的 ImageList 中的图像。ImageIndex 属性可以设置树视图中节点的默认图像。

在设计器中添加或移除节点
选择 TreeView 控件。

在“属性”窗口中,单击 Nodes 属性旁的“省略号”() 按钮。

显示“树节点编辑器”。

若要添加节点,必须存在根节点;如果不存在根节点,必须先单击“添加根”按钮添加一个根节点。然后,就可通过选择根节点或任何其他节点并单击“添加子级”按钮来添加子节点。

若要删除节点,请选择要删除的节点,然后单击“删除”按钮。

循环访问 TreeView 控件的所有节点
创建测试每个节点的递归过程(C# 和 C++ 中为递归方法)。

调用该过程。

下面的示例演示如何打印每个 TreeNode 对象的 Text 属性:

Visual Basic 复制代码
Private Sub PrintRecursive(ByVal n As TreeNode)
System.Diagnostics.Debug.WriteLine(n.Text)
MessageBox.Show(n.Text)
Dim aNode As TreeNode
For Each aNode In n.Nodes
PrintRecursive(aNode)
Next
End Sub

' Call the procedure using the top nodes of the treeview.
Private Sub CallRecursive(ByVal aTreeView As TreeView)
Dim n As TreeNode
For Each n In aTreeView.Nodes
PrintRecursive(n)
Next
End Sub

确定单击了哪个 TreeView 节点
使用 EventArgs 对象返回对已单击节点对象的引用。

通过检查 TreeViewEventArgs 类(它包含与事件有关的数据),确定单击了哪个节点。

Visual Basic 复制代码
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
' Determine by checking the Node property of the TreeViewEventArgs.
MessageBox.Show(e.Node.Text)
End Sub

建议下载安MSDN 上面给得比较详细 这里只拷一部分过来

WPF中TreeView控件的使用案例

WPF总体来说还是比较方便的,其中变化最大的主要是Listview和Treeview控件,而且TreeView似乎在WPF是一个备受指责的控件,很多人说他不好用。我这个demo主要是在wpf中使用TreeView控件实现图片查看功能,简单的Grid布局、TreeView控件添加图标、TreeView控件的一些事件、显示统计、还有就是读取文件操作。

效果图:

技术分享图片

前端主要代码:

<Window x:Class="TreeViewDemo.MainWindow"
        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"
        xmlns:local="clr-namespace:TreeViewDemo"
        mc:Ignorable="d"
        Title="WPF中TreeViewDemo" Height="964.8" Width="1718.2" Background="#FFEEEEEE" Loaded="Window_Loaded">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="166*"/>
            <ColumnDefinition Width="1545*"/>
        </Grid.ColumnDefinitions>
        <TabControl  
            SelectedIndex="{Binding Model.TabIndex,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
            HorizontalAlignment="Stretch" 
            SelectionChanged="TabControl_SelectionChanged"
            VerticalAlignment="Stretch" Background="White" Margin="5,0,10.333,0.333" Grid.ColumnSpan="2">
    
            <TabItem Header="照片预览" BorderBrush="#FFE8E8E8">
                <Grid>
                    <!--两行两列-->
                    <Grid.RowDefinitions>
                        <RowDefinition Height="50"/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="280"/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <StackPanel Grid.ColumnSpan="2"  Orientation="Horizontal" Margin="0,2,0,2">

                        <TextBlock VerticalAlignment="Center" FontSize="16">选中文件:</TextBlock>
                        <TextBlock VerticalAlignment="Center" FontSize="16" Text="{Binding Model.SelectFileleName}"></TextBlock>
                    </StackPanel>
                    <TreeView Grid.Column="0" Grid.Row="1" x:Name="departmentTree" PreviewMouseUp="departmentTree_PreviewMouseUp">
                        <TreeView.ItemTemplate>
                            <HierarchicalDataTemplate ItemsSource="{Binding Subitem}">
                                <StackPanel  Orientation="Horizontal" Margin="0,2,0,2">
                                    <Image  Source="{Binding Icon,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></Image>
                                    <!--<Image  Source="../refresh/folder.ico"></Image>--> 
                                    <TextBlock VerticalAlignment="Center" FontSize="14" Text="{Binding FileName}" ToolTip="{Binding FilePath,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBlock>
                                    <TextBlock VerticalAlignment="Center" FontSize="14" Text="{Binding SubitemCount}" FontWeight="Bold"></TextBlock>
                                </StackPanel>
                            </HierarchicalDataTemplate>
                        </TreeView.ItemTemplate>
                    </TreeView>


                    <!--照片-->
                    <Image Grid.Column="1" Grid.Row="1"  x:Name="MyImage"/>
                </Grid>

            </TabItem>
            <TabItem Header="设置" Width="64" BorderBrush="#FFEEEEEE">

            </TabItem>

        </TabControl>


    </Grid>
</Window>

 后端TreeView控件事件代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TreeViewDemo.ViewModel;

namespace TreeViewDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        MainWindowViewModel viewModel = new MainWindowViewModel();
        List<FileTreeModel> fileTreeData = new List<FileTreeModel>();
        public MainWindow()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 每一天照片统计
        /// </summary>
        public static int total = 0;
        /// <summary>
        /// 获取照片目录集合
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="d"></param>
        /// <returns></returns>
        public List<FileTreeModel> GetAllFiles(DirectoryInfo dir, FileTreeModel d)
        {
            List<FileTreeModel> FileList = new List<FileTreeModel>();
            FileInfo[] allFile = dir.GetFiles();
            total = allFile.Count();
            foreach (FileInfo fi in allFile)
                d.Subitem.Add(new FileTreeModel() { FileName = fi.Name, FilePath = fi.FullName, FileType = (int)FieleTypeEnum.Picture, Icon = "../refresh/picture.ico" });

            DirectoryInfo[] allDir = dir.GetDirectories();
            foreach (DirectoryInfo dif in allDir)
            {
                FileTreeModel fileDir = new FileTreeModel() { FileName = dif.Name, FilePath = dif.FullName, FileType = (int)FieleTypeEnum.Folder, Icon = "../refresh/folder.ico" };
                GetAllFiles(dif, fileDir);
                fileDir.SubitemCount = string.Format($"({total})");
                FileList.Add(fileDir);

            }
            return FileList;
        }
        /// <summary>
        /// Tab选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.Source is TabControl)
            {
                if (e.AddedItems != null && e.AddedItems.Count > 0)
                {
                    if (e.AddedItems[0] is TabItem)
                    {
                        TabItem tabItem = e.AddedItems[0] as TabItem;
                        if (tabItem.Header.ToString() == "过磅记录")
                        {

                        }
                        if (tabItem.Header.ToString() == "照片预览")
                        { 
                            string dataDir = AppDomain.CurrentDomain.BaseDirectory + "ImageLogs\\";

                            fileTreeData = GetAllFiles(new System.IO.DirectoryInfo(dataDir), new FileTreeModel()).OrderByDescending(s=>s.FileName).ToList();
                            this.departmentTree.ItemsSource = fileTreeData;
                        }
                    }
                }
            }
        }
          
        /// <summary>
        /// 文件树选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void departmentTree_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (departmentTree.SelectedItem != null)
                {
                    FileTreeModel selectedTnh = departmentTree.SelectedItem as FileTreeModel;
                    viewModel.Model.SelectFileleName = selectedTnh.FileName;

                    if (selectedTnh.FileType == (int)FieleTypeEnum.Picture)
                    {
                        BitmapImage imagesouce = new BitmapImage();
                        imagesouce = new BitmapImage(new Uri(selectedTnh.FilePath));//Uri("图片路径")
                        MyImage.Source = imagesouce.Clone();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
           

        } 
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // 绑定数据源
            this.DataContext = viewModel; 
        }


    }
}  

 

代码下载地址:https://download.csdn.net/download/qingchundaima/10671993

以上是关于treeview控件使用详解的主要内容,如果未能解决你的问题,请参考以下文章

Bootstrap树形菜单插件TreeView js使用方法详解

winform 中Treeview控件怎样选中父节点时子节点全部展开,选中其他父节点时原先展开的关闭

C# winform如何计算控件上文字的实际宽度(像素)

Python如何改变tkinter.ttk.Treeview表格组件的每行的行高?

winform控件布局(sidebar)

Android:ImageView控件的ScaleType属性使用详解