首页 > 代码库 > D22_05_treeview即时创建节点

D22_05_treeview即时创建节点

image

 

<Window x:Class="demo.DirectoryTreeView"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    Title="DirectoryTreeView" Height="300" Width="300"    >    <Grid Margin="3">        <!--TreeViewItem.Expanded展开事件-->      <TreeView Name="treeFileSystem" TreeViewItem.Expanded="item_Expanded">              </TreeView>    </Grid></Window>

DirectoryTreeView

using System;using System.Collections.Generic;using System.Text;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.Shapes;using System.IO;namespace demo{    /// <summary>    /// Interaction logic for DirectoryTreeView.xaml    /// </summary>    public partial class DirectoryTreeView : System.Windows.Window    {        public DirectoryTreeView()        {            InitializeComponent();            BuildTree();        }        private void BuildTree()        {            treeFileSystem.Items.Clear();            foreach (DriveInfo drive in DriveInfo.GetDrives())            {                TreeViewItem item = new TreeViewItem();                item.Tag = drive;                item.Header = drive.ToString();                                // This placeholder string is never shown,                // because the node begins in collapsed state.                //占位符,表示每个项可以折叠和收缩                item.Items.Add("X");                treeFileSystem.Items.Add(item);            }        }        private void item_Expanded(object sender, RoutedEventArgs e)        {            TreeViewItem item = (TreeViewItem)e.OriginalSource;            item.Items.Clear();            DirectoryInfo dir;            if (item.Tag is DriveInfo)            {                DriveInfo drive = (DriveInfo)item.Tag;                dir = drive.RootDirectory;            }            else            {                dir = (DirectoryInfo)item.Tag;            }            try            {                foreach (DirectoryInfo subDir in dir.GetDirectories())                {                    TreeViewItem newItem = new TreeViewItem();                    newItem.Tag = subDir;                    newItem.Header = subDir.ToString();                    newItem.Items.Add("X");                    item.Items.Add(newItem);                }            }            catch            {                            }        }           }}

D22_05_treeview即时创建节点