첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

■ TreeView 클래스 : 동적 노드 만들기

----------------------------------------------------------------------------------------------------


TestProject.zip


ImagedTreeViewItem.cs

 

 

using System.Windows;

using System.Windows.Controls;

using System.Windows.Media;

 

namespace TestProject

{

    /// <summary>

    /// 이미지 트리 뷰 항목

    /// </summary>

    public class ImagedTreeViewItem : TreeViewItem

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 이미지

        /// </summary>

        private Image image;

 

        /// <summary>

        /// 선택 이미지 소스

        /// </summary>

        private ImageSource selectedImageSource;

 

        /// <summary>

        /// 선택 해제 이미지 소스

        /// </summary>

        private ImageSource unselectedImageSource;

 

        /// <summary>

        /// 텍스트 블럭

        /// </summary>

        private TextBlock textBlock;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Property

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 선택 이미지 - SelectedImage

 

        /// <summary>

        /// 선택 이미지

        /// </summary>

        public ImageSource SelectedImage

        {

            set

            {

                this.selectedImageSource = value;

 

                if(IsSelected)

                {

                    this.image.Source = this.selectedImageSource;

                }

            }

            get

            {

                return this.selectedImageSource;

            }

        }

 

        #endregion

        #region 선택 해제 이미지 - UnselectedImage

 

        /// <summary>

        /// 선택 해제 이미지

        /// </summary>

        public ImageSource UnselectedImage

        {

            set

            {

                this.unselectedImageSource = value;

 

                if(!IsSelected)

                {

                    this.image.Source = this.unselectedImageSource;

                }

            }

            get

            {

                return this.unselectedImageSource;

            }

        }

 

        #endregion

        #region 텍스트 - Text

 

        /// <summary>

        /// 텍스트

        /// </summary>

        public string Text

        {

            set

            {

                this.textBlock.Text = value;

            }

            get

            {

                return this.textBlock.Text;

            }

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - ImagedTreeViewItem()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public ImagedTreeViewItem()

        {

            StackPanel stackPanel = new StackPanel();

 

            stackPanel.Orientation = Orientation.Horizontal;

 

            Header = stackPanel;

 

            this.image = new Image();

 

            this.image.VerticalAlignment = VerticalAlignment.Center;

            this.image.Margin            = new Thickness(0, 0, 2, 0);

 

            stackPanel.Children.Add(this.image);

 

            this.textBlock = new TextBlock();

 

            this.textBlock.VerticalAlignment = VerticalAlignment.Center;

 

            stackPanel.Children.Add(this.textBlock);

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Protected

 

        #region 선택시 처리하기 - OnSelected(e)

 

        /// <summary>

        /// 선택시 처리하기

        /// </summary>

        /// <param name="e">이벤트 인자</param>

        protected override void OnSelected(RoutedEventArgs e)

        {

            base.OnSelected(e);

 

            this.image.Source = this.selectedImageSource;

        }

 

        #endregion

        #region 선택 해제시 처리하기 - OnUnselected(e)

 

        /// <summary>

        /// 선택 해제시 처리하기

        /// </summary>

        /// <param name="e">이벤트 인자</param>

        protected override void OnUnselected(RoutedEventArgs e)

        {

            base.OnUnselected(e);

 

            this.image.Source = this.unselectedImageSource;

        }

 

        #endregion

    }

}

 

 

DirectoryTreeViewItem.cs

 

 

using System;

using System.IO;

using System.Windows;

using System.Windows.Media.Imaging;

 

namespace TestProject

{

    /// <summary>

    /// 디렉토리 트리 뷰 항목

    /// </summary>

    public class DirectoryTreeViewItem : ImagedTreeViewItem

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 디렉토리 정보

        /// </summary>

        private DirectoryInfo directoryInfo;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Propety

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 디렉토리 정보 - 디렉토리 정보

 

        /// <summary>

        /// 디렉토리 정보

        /// </summary>

        public DirectoryInfo DirectoryInfo

        {

            get

            {

                return this.directoryInfo;

            }

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - DirectoryTreeViewItem(pDirectoryInfo)

 

        /// <summary>

        /// 생성자

        /// </summary>

        /// <param name="pDirectoryInfo">디렉토리 정보</param>

        public DirectoryTreeViewItem(DirectoryInfo pDirectoryInfo)

        {

            this.directoryInfo = pDirectoryInfo;

 

            Text = pDirectoryInfo.Name;

 

            SelectedImage   = new BitmapImage(new Uri("pack://application:,,,/IMAGE/OPENFOLD.BMP"));

            UnselectedImage = new BitmapImage(new Uri("pack://application:,,,/IMAGE/CLSDFOLD.BMP"));

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 구축하기 - Populate()

 

        /// <summary>

        /// 구축하기

        /// </summary>

        public void Populate()

        {

            Items.Clear();

 

            DirectoryInfo[] subsidaryDirectoryInfoArray;

 

            try

            {

                subsidaryDirectoryInfoArray = this.directoryInfo.GetDirectories();

            }

            catch

            {

                return;

            }

 

            foreach(DirectoryInfo subsidaryDirectoryInfo in subsidaryDirectoryInfoArray)

            {

                Items.Add(new DirectoryTreeViewItem(subsidaryDirectoryInfo));

            }

        }

 

        #endregion

 

        ////////////////////////////////////////////////////////////////////////////////////////// Proptected

 

        #region 확장시 처리하기 - OnExpanded(e)

 

        /// <summary>

        /// 확장시 처리하기

        /// </summary>

        /// <param name="e">이벤트 인자</param>

        protected override void OnExpanded(RoutedEventArgs e)

        {

            base.OnExpanded(e);

 

            foreach(object item in Items)

            {

                DirectoryTreeViewItem directoryTreeViewItem = item as DirectoryTreeViewItem;

 

                directoryTreeViewItem.Populate();

            }

        }

 

        #endregion

    }

}

 

 

DirectoryTreeView.cs

 

 

using System;

using System.IO;

using System.Windows.Controls;

using System.Windows.Media.Imaging;

 

namespace TestProject

{

    /// <summary>

    /// 디렉토리 트리 뷰

    /// </summary>

    public class DirectoryTreeView : TreeView

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - DirectoryTreeView()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public DirectoryTreeView()

        {

            RefreshTree();

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 트리 갱신하기 - RefreshTree()

 

        /// <summary>

        /// 트리 갱신하기

        /// </summary>

        public void RefreshTree()

        {

            BeginInit();

 

            Items.Clear();

 

            DriveInfo[] driveInfoArray = DriveInfo.GetDrives();

 

            foreach(DriveInfo driveInfo in driveInfoArray)

            {

                char drive = driveInfo.Name.ToUpper()[0];

 

                DirectoryTreeViewItem directoryTreeViewItem = new DirectoryTreeViewItem(driveInfo.RootDirectory);

 

                if(drive != 'A' && drive != 'B' && driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0)

                {

                    directoryTreeViewItem.Text = string.Format("{0} ({1})", driveInfo.VolumeLabel, driveInfo.Name);

                }

                else

                {

                    directoryTreeViewItem.Text = string.Format("{0} ({1})", driveInfo.DriveType, driveInfo.Name);

                }

 

                if(drive == 'A' || drive == 'B')

                {

                    directoryTreeViewItem.SelectedImage = directoryTreeViewItem.UnselectedImage =

                        new BitmapImage(new Uri("pack://application:,,,/IMAGE/35FLOPPY.BMP"));

                }

                else if(driveInfo.DriveType == DriveType.CDRom)

                {

                    directoryTreeViewItem.SelectedImage = directoryTreeViewItem.UnselectedImage =

                        new BitmapImage(new Uri("pack://application:,,,/IMAGE/CDDRIVE.BMP"));

                }

                else

                {

                    directoryTreeViewItem.SelectedImage = directoryTreeViewItem.UnselectedImage =

                        new BitmapImage(new Uri("pack://application:,,,/IMAGE/DRIVE.BMP"));

                }

 

                Items.Add(directoryTreeViewItem);

 

                if(drive != 'A' && drive != 'B' && driveInfo.IsReady)

                {

                    directoryTreeViewItem.Populate();

                }

            }

 

            EndInit();

        }

 

        #endregion

    }

}

 

 

MainWindow.cs

 

 

using System;

using System.IO;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Media;

 

namespace TestProject

{

    /// <summary>

    /// 메인 윈도우

    /// </summary>

    public class MainWindow : Window

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 스택 패널

        /// </summary>

        private StackPanel stackPanel;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - MainWindow()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public MainWindow()

        {

            Width      = 800;

            Height     = 600;

            Title      = "TreeView 클래스 : 동적 노드 만들기";

            FontFamily = new FontFamily("나눔고딕코딩");

            FontSize   = 16;

 

            Grid grid = new Grid();

 

            Content = grid;

 

            #region 왼쪽 컬럼 정의를 생성한다.

 

            ColumnDefinition leftColumnDefinition = new ColumnDefinition();

 

            leftColumnDefinition.Width = new GridLength(50, GridUnitType.Star);

 

            grid.ColumnDefinitions.Add(leftColumnDefinition);

 

            #endregion

            #region 가운데 컬럼 정의를 생성한다.

 

            ColumnDefinition centerColumnDefinition = new ColumnDefinition();

 

            centerColumnDefinition.Width = GridLength.Auto;

 

            grid.ColumnDefinitions.Add(centerColumnDefinition);

 

            #endregion

            #region 오른쪽 컬럼 정의를 생성한다.

 

            ColumnDefinition rightColumnDefinition = new ColumnDefinition();

 

            rightColumnDefinition.Width = new GridLength(50, GridUnitType.Star);

 

            grid.ColumnDefinitions.Add(rightColumnDefinition);

 

            #endregion

            #region 디렉토리 트리 뷰를 생성한다.

 

            DirectoryTreeView directoryTreeView = new DirectoryTreeView();

 

            directoryTreeView.SelectedItemChanged += directoryTreeView_SelectedItemChanged;

 

            grid.Children.Add(directoryTreeView);

 

            Grid.SetColumn(directoryTreeView, 0);

 

            #endregion

            #region 그리드 스플리터를 생성한다.

 

            GridSplitter gridSplitter = new GridSplitter();

 

            gridSplitter.Width          = 6;

            gridSplitter.ResizeBehavior = GridResizeBehavior.PreviousAndNext;

 

            grid.Children.Add(gridSplitter);

 

            Grid.SetColumn(gridSplitter, 1);

 

            #endregion

            #region 스크롤 뷰어를 생성한다.

 

            ScrollViewer scrollViewer = new ScrollViewer();

 

            grid.Children.Add(scrollViewer);

 

            Grid.SetColumn(scrollViewer, 2);

 

            #endregion

            #region 스택 패널을 생성한다.

 

            this.stackPanel = new StackPanel();

 

            scrollViewer.Content = this.stackPanel;

 

            #endregion

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Static

        //////////////////////////////////////////////////////////////////////////////// Public

 

        #region 프로그램 시작하기 - Main()

 

        /// <summary>

        /// 프로그램 시작하기

        /// </summary>

        [STAThread]

        public static void Main()

        {

            Application application = new Application();

 

            application.Run(new MainWindow());

        }

 

        #endregion

 

        ////////////////////////////////////////////////////////////////////////////////////////// Instance

        //////////////////////////////////////////////////////////////////////////////// Private

 

        #region 디렉토리 트리 뷰 선택 항목 변경시 처리하기 - directoryTreeView_SelectedItemChanged(sender, e)

 

        /// <summary>

        /// 디렉토리 트리 뷰 선택 항목 변경시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void directoryTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)

        {

            DirectoryTreeViewItem directoryTreeViewItem = e.NewValue as DirectoryTreeViewItem;

 

            this.stackPanel.Children.Clear();

 

            FileInfo[] fileInfoArray;

 

            try

            {

                fileInfoArray = directoryTreeViewItem.DirectoryInfo.GetFiles();

            }

            catch

            {

                return;

            }

 

            foreach(FileInfo fileInfo in fileInfoArray)

            {

                TextBlock textBlock = new TextBlock();

 

                textBlock.Text = fileInfo.Name;

 

                this.stackPanel.Children.Add(textBlock);

            }

        }

 

        #endregion

    }

}

 

----------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker
TAG

댓글을 달아 주세요